Rails 4.0

3,175 views

Published on

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,175
On SlideShare
0
From Embeds
0
Number of Embeds
48
Actions
Shares
0
Downloads
27
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Rails 4.0

  1. 1. 4.0
  2. 2. Highlights in Rails 4.0• At least Ruby 1.9.3• Thread safe by default• Strong Parameters• Turbolinks• Russian Doll Caching
  3. 3. Removed from master• Rails.queue (ActiveSupport::Queue) => 4.1• Asynchronous Action Mailer => 4.1
  4. 4. Extracted Gems• Sprockets Rails• ActiveResource• AR Observer + AC Sweeper• AR SessionStore• AR deprecated_finders• ...
  5. 5. Deprecation Policy• 4.0 mostly just deprecates• 4.1 removes those features So manually add the gems to Gemfile• 5.0 removes support for some of those gems
  6. 6. Strong ParametersMass assignment protection on controllers
  7. 7. Rails 3class  Post  <  Ac+veRecord::Base    a3r_accessible  :+tle,  :bodyendclass  PostsController  <  Applica+onController    def  create        @post  =  Post.create(params[:post])    endend
  8. 8. Rails 4class  Post  <  Ac+veRecord::Baseendclass  PostsController  <  Applica+onController    def  create        @post  =  Post.create(post_params)    end    private    def  post_params        params.require(:post).            permit(:-tle,  :body)    endend
  9. 9. Permitted Scalar Values params.permit(:id)• key id passes whitelisting if it appears in params and it has a permitted scalar value associated• disallowed keys: development and test => log, other env => filter it out
  10. 10. Scalar ValuesString, Symbol, NilClass, Numeric, TrueClass,FalseClass, Date, Time, DateTime, StringIO,IO and ActionDispatch::Http::UploadedFile
  11. 11. Permit an Array params.permit(:tags => [])• must be an array of permitted scalar values
  12. 12. Nested Parametersparams.permit( :name, { :emails => []}, :friends => [ :name, { :family => [ :name ] }])
  13. 13. ProtectedAttributes• attr_accessible / attr_proteced removed• https://github.com/rails/protected_attributes
  14. 14. Use it today• https://github.com/rails/strong_parameters• Rails 3.x• include ActiveModel::ForbiddenAttributesProtection
  15. 15. TurbolinksMakes following links faster
  16. 16. Live Demo
  17. 17. Turbolinks• Activated by default• Doesn’t reinterpret JavaScript and CSS each time the page loads• Similar to pjax• Use it today! https://github.com/rails/turbolinks
  18. 18. Russian Doll Caching Cache Digests
  19. 19. ‘Definition’The technique of nesting fragment caches tomaximize cache hits is known as russian dollcaching.
  20. 20. Example Modelclass  Team  <  Ac+veRecord::Base    has_many  :membersendclass  Member  <  Ac+veRecord::Base    belongs_to  :team,  touch:  trueend
  21. 21. Example Modelclass  Team  <  Ac+veRecord::Base    has_many  :membersendclass  Member  <  Ac+veRecord::Base    belongs_to  :team,  touch:  trueend
  22. 22. Example Template<!-­‐-­‐  app/views/teams/show.html.erb  -­‐-­‐><%  cache  @team  do%>    <h1>Team:  <%=  @team.name  %></h1>    <%=  render  @team.members  %><%  end  %><!-­‐-­‐  app/views/members/_member.html.erb  -­‐-­‐><%  cache  member  do  %>    <div  class=member>        <%=  member.name  %>        <p><%=  member.bio  %></p>    </div><%  end  %>
  23. 23. Fragment Caches Example•views/members/1-­‐20121220141922•views/members/2-­‐20121220141922•views/teams/2-­‐20121220141922
  24. 24. Versioning<!-­‐-­‐  app/views/teams/show.html.erb  -­‐-­‐><%  cache  ["v1",  @team]  do%>    <h1>Team:  <%=  @team.name  %></h1>    <%=  render  @team.members  %><%  end  %><!-­‐-­‐  app/views/members/_member.html.erb  -­‐-­‐><%  cache  ["v1",  member]  do  %>    <div  class=member>        <span><%=  member.name  %></span>        <p><%=  member.bio  %></p>    </div><%  end  %>
  25. 25. Fragment Caches Example•views/v1/members/1-­‐20121220141922•views/v1/members/2-­‐20121220141922•views/v1/teams/2-­‐20121220141922
  26. 26. Cache Digests• Rails 4 will suffix a digest of the template and its dependencies• Don’t worry about fragment cache dependencies and versioning!
  27. 27. Fragment Caches Example• views/members/1-­‐20121220141922/74865fcb3e2752a0928fa4f89b3e4426• views/members/2-­‐20121220141922/74865fcb3e2752a0928fa4f89b3e4426• views/teams/2-­‐20121220141922/4277f85c137009873c093088ef609e60
  28. 28. Rake Tasks$  rake  cache_digests:dependencies                                                          TEMPLATE=projects/show[    “teams/show”,    “members/member”]$  rake  cache_digests:nested_dependencies                                                          TEMPLATE=projects/show
  29. 29. Caching Deprecations• Action and Page caching has been extracted• https://github.com/rails/actionpack-action_caching• https://github.com/rails/actionpack-page_caching
  30. 30. HTTP PATCH Verb for partial updates
  31. 31. RFC 5789"In a PUT request, the enclosed entity isconsidered to be a modified version of the resourcestored on the origin server, and the client isrequesting that the stored version be replaced.With PATCH, however, the enclosed entity containsa set of instructions describing how a resourcecurrently residing on the origin server should bemodified to produce a new version."
  32. 32. Changes• PATCH is going to be the primary method for updates• will be backward compatible• PUT requests get routed to update as they are today• Forms will set the hidden field _method to :patch on edits
  33. 33. RailtiesGluing the Engine to the Rails
  34. 34. Rails::Plugin has gone• vendor/plugins is no more• use gems or• bundler with path or git dependencies
  35. 35. Dynamic index.html • Rails::WelcomeController serves dynamic welcome screen • Disable by defining root route in routes.rb
  36. 36. rails/info/routes
  37. 37. Action Controller
  38. 38. Rename all action callbacks from *_filter to *_action class  PeopleController  <  Ac+onController::Base    before_ac+on  :set_person,  except:  [  :index,  :new,  :create  ]    before_ac+on  :ensure_permission,  :only:  [  :edit,  :update  ]    #  ...    private    def  set_person        @person  =  current_account.people.find(params[:id])    end    def  ensure_permission        current_person.can_change?(@person)    end end
  39. 39. Register Your Own Flash Types#  Rails  3class  PostsController    def  create        ... flash[:error]  =  “my  error” redirect_to  home_path    endend#  app/views/home/index<%=  flash[:error]  %>
  40. 40. Register Your Own Flash Types#  Rails  4class  ApplicaIonController    add_flash_types  :error,  :warningendclass  PostsController    def  create        ...        redirect_to  home_path,  error:  “my  error”    endend#  app/views/home/index<%=  error  %>
  41. 41. Action Dispatch
  42. 42. Root#  config/routes.rb        Rails  3root  :to  =>  ‘pages#main’#  config/routes.rb        Rails  4root  ‘pages#main’
  43. 43. Unicode Characters in Routes#  config/routes.rb        Rails  3get  Rack::U+ls.escape("Fußball")  =>  sports#football#  config/routes.rb        Rails  4get  ‘Fußball’  =>  ‘sports#football’
  44. 44. Routing Concerns #  config/routes.rb        Rails  3 resources  :messages  do    resources  :comments end resources  :posts  do    resources  :comments    resources  :images,  only:  index end
  45. 45. Routing Concerns#  config/routes.rb        Rails  4concern  :commentable  do    resources  :commentsendconcern  :image_aOachable  do    resources  :images,  only:  indexendresources  :messages,  concerns:  :commentableresources  :posts,  concerns:                                                                    [:commentable,  :image_aOachable]
  46. 46. Matchmatch  /about  =>  generals#about,  as:  :about • old DSL will match all verbs for the path to the specified endpoint, use :via => :all • most of the time you actually mean +get+ • use HTTP verbs!get  /about  =>  generals#about,  as:  :about
  47. 47. Active Record
  48. 48. No More Rails 2 Finder Syntax User.find(:all,  ...) User.find(:first,  ...) User.find(:last,  ...)
  49. 49. Model.all returns relation#  Rails  3>  Post.all.where(+tle:  “RUGSAAR”)=>  NoMethodError:  undefined  method  `where  for  []:Array#  Rails  4>  Post.all.where(+tle:  “RUGSAAR”).to_a
  50. 50. NOT Ar-cle.where("-tle  !=  ?",    -tle)Ar-cle.where.not(-tle:  Rails  3)#  >>  SELECT  "ar,cles".*  FROM  "ar,cles"  WHERE  ("ar,cles".",tle"  !=  Rails  3)Ar-cle.where.not(-tle:  [Rails  3,  Rails  5])#  >>  SELECT  "ar,cles".*  FROM  "ar,cles"  WHERE  ("ar,cles".",tle"  NOT  IN  (Rails  3,  Rails  5))
  51. 51. Whiny nil#  Rails  3>  nil.id=>  Run+meError:  Called  id  for  nil,  which  would  mistakenly  be  4  -­‐-­‐  if  you  really  wanted  the  id  of  nil,  use  object_id#  Rails  4>  nil.id=>  NoMethodError:  undefined  method  ‘id’  for  nil:nilClass
  52. 52. .first and .last ordering #  Rails  3 >  Post.first SELECT  “posts”.*  FROM  “posts”  LIMIT  1 #  Rails  4 >  Post.first SELECT  “posts”.*  FROM  “posts”    ORDER  BY  “posts”.”id”  ASC  LIMIT  1
  53. 53. Eager-evaluated scopes#  Deprecatedscope  :published,                where(:published  =>  true)#  Pioallscope  :recent,                where(“created_at  >  ?”,  1.week.ago)#  use  a  lamda  (always,  not  just  for  +me!)scope  :published,                -­‐>  {  where(:published  =>  true)  }
  54. 54. update_(attribute|column)s? Dirty updated_at Validations run? Callbacks run? attributes touched? updated?update_attributes( Yes Yes Yes Yes:name => “value”)update_attribute( No Yes Yes Yes :name, “value”) update_columns( No No No No:name => “values”) update_column( No No No No :name, “value”) update_attributes => update
  55. 55. Dynamic Findersfind_by_. . . OKfind_by_....!find_all_by_. . . where(. . .)scoped_by_....find_last_by_. . . where(. . .).last where(. . .).find_or_initialize_by_. . . first_or_initialize where(. . .).find_or_create_by_. . . first_or_create where(. . .).find_or_create_by_. . .! first_or_create!
  56. 56. find_by and find_by!Post.find_by_name_and_rating(Spartacus, 4)Post.find_by name: Spartacus, rating: 4Post.find_by! name: Spartacus
  57. 57. :-(• Binstubs• ActionView (new html5 and collection form helpers, ...)• MiniTest• PostgreSQL (hstore, array, date ranges, ...)• ...
  58. 58. Dankehttp://blog.wyeworks.com/2012/11/13/rails-4-compilation-links/
  59. 59. Dankehttp://blog.wyeworks.com/2012/11/13/rails-4-compilation-links/

×