SlideShare uma empresa Scribd logo
1 de 62
Baixar para ler offline
4.0
Highlights in Rails 4.0

• At least Ruby 1.9.3
• Thread safe by default
• Strong Parameters
• Turbolinks
• Russian Doll Caching
Removed from master


• Rails.queue (ActiveSupport::Queue) => 4.1
• Asynchronous Action Mailer => 4.1
Extracted Gems

• Sprockets Rails
• ActiveResource
• AR Observer + AC Sweeper
• AR SessionStore
• AR deprecated_finders
• ...
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
Strong Parameters
Mass assignment protection on controllers
Rails 3
class	
  Post	
  <	
  Ac+veRecord::Base
	
  	
  a3r_accessible	
  :+tle,	
  :body
end

class	
  PostsController	
  <	
  Applica+onController
	
  	
  def	
  create
	
  	
  	
  	
  @post	
  =	
  Post.create(params[:post])
	
  	
  end
end
Rails 4
class	
  Post	
  <	
  Ac+veRecord::Base
end

class	
  PostsController	
  <	
  Applica+onController
	
  	
  def	
  create
	
  	
  	
  	
  @post	
  =	
  Post.create(post_params)
	
  	
  end

	
  	
  private

	
  	
  def	
  post_params
	
  	
  	
  	
  params.require(:post).
	
  	
  	
  	
  	
  	
  permit(:-tle,	
  :body)
	
  	
  end
end
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
Scalar Values


String, Symbol, NilClass, Numeric, TrueClass,
FalseClass, Date, Time, DateTime, StringIO,
IO and ActionDispatch::Http::UploadedFile
Permit an Array

          params.permit(:tags => [])




• must be an array of permitted scalar values
Nested Parameters

params.permit(
  :name,
  { :emails => []},
  :friends => [ :name, { :family => [ :name ] }]
)
ProtectedAttributes


• attr_accessible / attr_proteced removed
• https://github.com/rails/protected_attributes
Use it today

• https://github.com/rails/strong_parameters
•   Rails 3.x

•   include
    ActiveModel::ForbiddenAttributesProtection
Turbolinks
Makes following links faster
Live Demo
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
Russian Doll Caching
       Cache Digests
‘Definition’

The technique of nesting fragment caches to
maximize cache hits is known as russian doll
caching.
Example Model
class	
  Team	
  <	
  Ac+veRecord::Base
	
  	
  has_many	
  :members
end

class	
  Member	
  <	
  Ac+veRecord::Base
	
  	
  belongs_to	
  :team,	
  touch:	
  true
end
Example Model
class	
  Team	
  <	
  Ac+veRecord::Base
	
  	
  has_many	
  :members
end

class	
  Member	
  <	
  Ac+veRecord::Base
	
  	
  belongs_to	
  :team,	
  touch:	
  true
end
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	
  %>
Fragment Caches
        Example
•views/members/1-­‐20121220141922
•views/members/2-­‐20121220141922
•views/teams/2-­‐20121220141922
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	
  %>
Fragment Caches
        Example
•views/v1/members/1-­‐20121220141922
•views/v1/members/2-­‐20121220141922
•views/v1/teams/2-­‐20121220141922
Cache Digests

• Rails 4 will suffix a digest of the template
  and its dependencies
• Don’t worry about fragment cache
  dependencies and versioning!
Fragment Caches
              Example
• views/members/1-­‐20121220141922/74865fcb3e2752a0928fa4f89b3e4426
• views/members/2-­‐20121220141922/74865fcb3e2752a0928fa4f89b3e4426
• views/teams/2-­‐20121220141922/4277f85c137009873c093088ef609e60
Rake Tasks
$	
  rake	
  cache_digests:dependencies	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  TEMPLATE=projects/show

[
	
  	
  “teams/show”,
	
  	
  “members/member”
]

$	
  rake	
  cache_digests:nested_dependencies	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  TEMPLATE=projects/show
Caching Deprecations

• Action and Page caching has been
    extracted
•   https://github.com/rails/actionpack-action_caching

•   https://github.com/rails/actionpack-page_caching
HTTP PATCH Verb
    for partial updates
RFC 5789
"In a PUT request, the enclosed entity is
considered to be a modified version of the resource
stored on the origin server, and the client is
requesting that the stored version be replaced.
With PATCH, however, the enclosed entity contains
a set of instructions describing how a resource
currently residing on the origin server should be
modified to produce a new version."
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
Railties
Gluing the Engine to the Rails
Rails::Plugin has gone

• vendor/plugins is no more
• use gems or
• bundler with path or git dependencies
Dynamic index.html
       • Rails::WelcomeController
         serves dynamic welcome
         screen
       • Disable by defining root route
         in routes.rb
rails/info/routes
Action Controller
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
Register Your Own
       Flash Types
#	
  Rails	
  3
class	
  PostsController
	
  	
  def	
  create
	
  	
  	
  	
  ...
                flash[:error]	
  =	
  “my	
  error”
                redirect_to	
  home_path
	
  	
  end
end

#	
  app/views/home/index
<%=	
  flash[:error]	
  %>
Register Your Own
      Flash Types
#	
  Rails	
  4
class	
  ApplicaIonController
	
  	
  add_flash_types	
  :error,	
  :warning
end

class	
  PostsController
	
  	
  def	
  create
	
  	
  	
  	
  ...
	
  	
  	
  	
  redirect_to	
  home_path,	
  error:	
  “my	
  error”
	
  	
  end
end

#	
  app/views/home/index
<%=	
  error	
  %>
Action Dispatch
Root
#	
  config/routes.rb	
  	
  	
  	
  Rails	
  3
root	
  :to	
  =>	
  ‘pages#main’

#	
  config/routes.rb	
  	
  	
  	
  Rails	
  4
root	
  ‘pages#main’
Unicode Characters in
           Routes
#	
  config/routes.rb	
  	
  	
  	
  Rails	
  3
get	
  Rack::U+ls.escape("Fußball")	
  =>	
  'sports#football'

#	
  config/routes.rb	
  	
  	
  	
  Rails	
  4
get	
  ‘Fußball’	
  =>	
  ‘sports#football’
Routing Concerns
   #	
  config/routes.rb	
  	
  	
  	
  Rails	
  3
   resources	
  :messages	
  do
   	
  	
  resources	
  :comments
   end

   resources	
  :posts	
  do
   	
  	
  resources	
  :comments
   	
  	
  resources	
  :images,	
  only:	
  index
   end
Routing Concerns
#	
  config/routes.rb	
  	
  	
  	
  Rails	
  4
concern	
  :commentable	
  do
	
  	
  resources	
  :comments
end

concern	
  :image_aOachable	
  do
	
  	
  resources	
  :images,	
  only:	
  index
end

resources	
  :messages,	
  concerns:	
  :commentable
resources	
  :posts,	
  concerns:	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [:commentable,	
  :image_aOachable]
Match
match	
  '/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
Active Record
No More Rails 2 Finder
      Syntax
     User.find(:all,	
  ...)
     User.find(:first,	
  ...)
     User.find(:last,	
  ...)
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
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'))
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
.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
Eager-evaluated scopes
#	
  Deprecated
scope	
  :published,
	
  	
  	
  	
  	
  	
  	
  	
  where(:published	
  =>	
  true)

#	
  Pioall
scope	
  :recent,
	
  	
  	
  	
  	
  	
  	
  	
  where(“created_at	
  >	
  ?”,	
  1.week.ago)

#	
  use	
  a	
  lamda	
  (always,	
  not	
  just	
  for	
  +me!)
scope	
  :published,
	
  	
  	
  	
  	
  	
  	
  	
  -­‐>	
  {	
  where(:published	
  =>	
  true)	
  }
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
Dynamic Finders
find_by_. . .
                             OK
find_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!
find_by and find_by!
Post.find_by_name_and_rating('Spartacus', 4)



Post.find_by name: 'Spartacus', rating: 4


Post.find_by! name: 'Spartacus'
:-(

• Binstubs
• ActionView (new html5 and collection
  form helpers, ...)
• MiniTest
• PostgreSQL (hstore, array, date ranges, ...)
• ...
Danke
http://blog.wyeworks.com/2012/11/13/rails-4-compilation-links/
Danke
http://blog.wyeworks.com/2012/11/13/rails-4-compilation-links/

Mais conteúdo relacionado

Mais procurados

Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineDavid Keener
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stackPaul Bearne
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyLaunchAny
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Henry S
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Vikas Chauhan
 
Routing 1, Season 1
Routing 1, Season 1Routing 1, Season 1
Routing 1, Season 1RORLAB
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2RORLAB
 
Bullet: The Functional PHP Micro-Framework
Bullet: The Functional PHP Micro-FrameworkBullet: The Functional PHP Micro-Framework
Bullet: The Functional PHP Micro-FrameworkVance Lucas
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发shaokun
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers StealBen Scofield
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
Building Cloud Castles - LRUG
Building Cloud Castles - LRUGBuilding Cloud Castles - LRUG
Building Cloud Castles - LRUGBen Scofield
 
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017Ryan Weaver
 
Ruby MVC from scratch with Rack
Ruby MVC from scratch with RackRuby MVC from scratch with Rack
Ruby MVC from scratch with RackDonSchado
 

Mais procurados (20)

Javascript laravel's friend
Javascript laravel's friendJavascript laravel's friend
Javascript laravel's friend
 
Supa fast Ruby + Rails
Supa fast Ruby + RailsSupa fast Ruby + Rails
Supa fast Ruby + Rails
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search Engine
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3
 
Rails3 changesets
Rails3 changesetsRails3 changesets
Rails3 changesets
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
Routing 1, Season 1
Routing 1, Season 1Routing 1, Season 1
Routing 1, Season 1
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Bullet: The Functional PHP Micro-Framework
Bullet: The Functional PHP Micro-FrameworkBullet: The Functional PHP Micro-Framework
Bullet: The Functional PHP Micro-Framework
 
Workshop Laravel 5.2
Workshop Laravel 5.2Workshop Laravel 5.2
Workshop Laravel 5.2
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers Steal
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Building Cloud Castles - LRUG
Building Cloud Castles - LRUGBuilding Cloud Castles - LRUG
Building Cloud Castles - LRUG
 
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Ruby MVC from scratch with Rack
Ruby MVC from scratch with RackRuby MVC from scratch with Rack
Ruby MVC from scratch with Rack
 

Semelhante a Rails 4.0

Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) RoundupWayne Carter
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2Rory Gianni
 
Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3Clinton Dreisbach
 
wwc start-launched
wwc start-launchedwwc start-launched
wwc start-launchedMat Schaffer
 
PTW Rails Bootcamp
PTW Rails BootcampPTW Rails Bootcamp
PTW Rails BootcampMat Schaffer
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à RubyMicrosoft
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009bturnbull
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5Bukhori Aqid
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkBen Scofield
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails DevsDiacode
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortegaarman o
 
Rack is Spectacular
Rack is SpectacularRack is Spectacular
Rack is SpectacularBryce Kerley
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentNicolas Ledez
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialYi-Ting Cheng
 
Integrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby AmfIntegrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby Amfrailsconf
 

Semelhante a Rails 4.0 (20)

Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) Roundup
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2
 
Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
wwc start-launched
wwc start-launchedwwc start-launched
wwc start-launched
 
PTW Rails Bootcamp
PTW Rails BootcampPTW Rails Bootcamp
PTW Rails Bootcamp
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à Ruby
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortega
 
Rack is Spectacular
Rack is SpectacularRack is Spectacular
Rack is Spectacular
 
Intro to Rails 4
Intro to Rails 4Intro to Rails 4
Intro to Rails 4
 
Rails3 way
Rails3 wayRails3 way
Rails3 way
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Integrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby AmfIntegrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby Amf
 

Último

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 

Último (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 

Rails 4.0

  • 1. 4.0
  • 2. Highlights in Rails 4.0 • At least Ruby 1.9.3 • Thread safe by default • Strong Parameters • Turbolinks • Russian Doll Caching
  • 3. Removed from master • Rails.queue (ActiveSupport::Queue) => 4.1 • Asynchronous Action Mailer => 4.1
  • 4. Extracted Gems • Sprockets Rails • ActiveResource • AR Observer + AC Sweeper • AR SessionStore • AR deprecated_finders • ...
  • 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. Strong Parameters Mass assignment protection on controllers
  • 7. Rails 3 class  Post  <  Ac+veRecord::Base    a3r_accessible  :+tle,  :body end class  PostsController  <  Applica+onController    def  create        @post  =  Post.create(params[:post])    end end
  • 8. Rails 4 class  Post  <  Ac+veRecord::Base end class  PostsController  <  Applica+onController    def  create        @post  =  Post.create(post_params)    end    private    def  post_params        params.require(:post).            permit(:-tle,  :body)    end end
  • 9.
  • 10. 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
  • 11. Scalar Values String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO and ActionDispatch::Http::UploadedFile
  • 12. Permit an Array params.permit(:tags => []) • must be an array of permitted scalar values
  • 13. Nested Parameters params.permit( :name, { :emails => []}, :friends => [ :name, { :family => [ :name ] }] )
  • 14. ProtectedAttributes • attr_accessible / attr_proteced removed • https://github.com/rails/protected_attributes
  • 15. Use it today • https://github.com/rails/strong_parameters • Rails 3.x • include ActiveModel::ForbiddenAttributesProtection
  • 18. 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
  • 19. Russian Doll Caching Cache Digests
  • 20. ‘Definition’ The technique of nesting fragment caches to maximize cache hits is known as russian doll caching.
  • 21. Example Model class  Team  <  Ac+veRecord::Base    has_many  :members end class  Member  <  Ac+veRecord::Base    belongs_to  :team,  touch:  true end
  • 22. Example Model class  Team  <  Ac+veRecord::Base    has_many  :members end class  Member  <  Ac+veRecord::Base    belongs_to  :team,  touch:  true end
  • 23. 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  %>
  • 24. Fragment Caches Example •views/members/1-­‐20121220141922 •views/members/2-­‐20121220141922 •views/teams/2-­‐20121220141922
  • 25. 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  %>
  • 26. Fragment Caches Example •views/v1/members/1-­‐20121220141922 •views/v1/members/2-­‐20121220141922 •views/v1/teams/2-­‐20121220141922
  • 27. Cache Digests • Rails 4 will suffix a digest of the template and its dependencies • Don’t worry about fragment cache dependencies and versioning!
  • 28. Fragment Caches Example • views/members/1-­‐20121220141922/74865fcb3e2752a0928fa4f89b3e4426 • views/members/2-­‐20121220141922/74865fcb3e2752a0928fa4f89b3e4426 • views/teams/2-­‐20121220141922/4277f85c137009873c093088ef609e60
  • 29. Rake Tasks $  rake  cache_digests:dependencies                                                          TEMPLATE=projects/show [    “teams/show”,    “members/member” ] $  rake  cache_digests:nested_dependencies                                                          TEMPLATE=projects/show
  • 30. Caching Deprecations • Action and Page caching has been extracted • https://github.com/rails/actionpack-action_caching • https://github.com/rails/actionpack-page_caching
  • 31. HTTP PATCH Verb for partial updates
  • 32. RFC 5789 "In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version."
  • 33. 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
  • 35. Rails::Plugin has gone • vendor/plugins is no more • use gems or • bundler with path or git dependencies
  • 36. Dynamic index.html • Rails::WelcomeController serves dynamic welcome screen • Disable by defining root route in routes.rb
  • 38.
  • 39.
  • 41. 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
  • 42. Register Your Own Flash Types #  Rails  3 class  PostsController    def  create        ... flash[:error]  =  “my  error” redirect_to  home_path    end end #  app/views/home/index <%=  flash[:error]  %>
  • 43. Register Your Own Flash Types #  Rails  4 class  ApplicaIonController    add_flash_types  :error,  :warning end class  PostsController    def  create        ...        redirect_to  home_path,  error:  “my  error”    end end #  app/views/home/index <%=  error  %>
  • 45. Root #  config/routes.rb        Rails  3 root  :to  =>  ‘pages#main’ #  config/routes.rb        Rails  4 root  ‘pages#main’
  • 46. Unicode Characters in Routes #  config/routes.rb        Rails  3 get  Rack::U+ls.escape("Fußball")  =>  'sports#football' #  config/routes.rb        Rails  4 get  ‘Fußball’  =>  ‘sports#football’
  • 47. Routing Concerns #  config/routes.rb        Rails  3 resources  :messages  do    resources  :comments end resources  :posts  do    resources  :comments    resources  :images,  only:  index end
  • 48. Routing Concerns #  config/routes.rb        Rails  4 concern  :commentable  do    resources  :comments end concern  :image_aOachable  do    resources  :images,  only:  index end resources  :messages,  concerns:  :commentable resources  :posts,  concerns:                                                                    [:commentable,  :image_aOachable]
  • 49. Match match  '/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
  • 51. No More Rails 2 Finder Syntax User.find(:all,  ...) User.find(:first,  ...) User.find(:last,  ...)
  • 52. 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
  • 53. 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'))
  • 54. 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
  • 55. .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
  • 56. Eager-evaluated scopes #  Deprecated scope  :published,                where(:published  =>  true) #  Pioall scope  :recent,                where(“created_at  >  ?”,  1.week.ago) #  use  a  lamda  (always,  not  just  for  +me!) scope  :published,                -­‐>  {  where(:published  =>  true)  }
  • 57. 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
  • 58. Dynamic Finders find_by_. . . OK find_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!
  • 59. find_by and find_by! Post.find_by_name_and_rating('Spartacus', 4) Post.find_by name: 'Spartacus', rating: 4 Post.find_by! name: 'Spartacus'
  • 60. :-( • Binstubs • ActionView (new html5 and collection form helpers, ...) • MiniTest • PostgreSQL (hstore, array, date ranges, ...) • ...