SlideShare a Scribd company logo
1 of 31
Rails 3 For Rails 2 Developers
Components
Lifecycle
Controller Stack
Creating a Rails 3 app rvmgemset create rails3 rvmgemset use rails3 gem install rails --pre rails new test_app
Scripts
Look at: environment.rb application.rb config.ru
Routes - compatibility Old Style TestApp::Application.routes.drawdo |map| map.resources:posts do |post|post.resources:comments end end New Style TestApp::Application.routes.drawdo |map|resources:posts do resources :comments end end
Routes - resources Old Style post.resources:comments, :member => { :preview => :post }, :collection => { :archived => :get } New Style resources :comments do post :preview, :on => :member get :archived, :on => :collection end
Routes – named routes Old Style map.connect'login’, :controller => 'session', :action => 'new' map.login'login’, :controller => 'session', :action => 'new’ New Style match 'login' => 'session#new’ match 'login' => 'session#new', :as => :login
Routes – root paths Old Style map.root:controller => 'users’, :action => 'index’ New Style root :to => 'users#index'
Routes - Rack Endpoints get 'hello' => proc { |env| [200, {}, "Hello Rack"] } get 'rack_endpoint' => PostsController.action(:index) get 'rack_app' => CustomRackApp
Routes Etc. Documentation here: http://guides.rails.info/routing.html
ActionController – Legacy Style class UsersController< ApplicationController def index @users = User.all respond_todo |format| format.html format.xml{ render :xml => @users.to_xml} end 	end 	def show @user = User.find(params[:id]) respond_todo |format| format.html# show.html.erb format.xml{ render :xml => @user } 		end  	end end
ActionController – New Style class UsersController< ApplicationControllerrespond_to:html, :xml, :json def index @users = User.all respond_with(@users) end def show @user = User.find(params[:id]) respond_with(@user) end end
ActionMailer def welcome(user, subdomain) @user = user @subdomain= subdomain mail(:from=>admin@testapp.com, :to => user.email, 		:subject => "Welcome to TestApp") End UserMailer.welcome(user, subdomain).deliver
ActionMailer class UserMailer< ActionMailer::Base default :from => "admin@testapp.com", :reply_to=> "noreply@testapp.com", "X-Time-Code" => Time.now.to_i.to_s def welcome(user, subdomain) @user = user @subdomain= subdomain attachments['test.pdf'] = File.read("#{Rails.root}/public/test.pdf") mail(:to=> @user.email, :subject => "Welcome to TestApp") do |format|format.html{ render 'other_html_welcome' } format.text{ render 'other_text_welcome' } end  	end end
ActiveRelation Rails2 @posts = Post.find(:all, :conditions => {:published => true}) @posts = Post.find(:all, :conditions => {:author => "Joe"}, :includes => :comments, :order => "title", :limit => 10) Rails3 @posts = Post.where(:published=> true) @posts = Post.where(:author=> "Joe").include(:comments).order(:title).limit(10).all
ActiveRelation - scopes Rails2 class Post < ActiveRecord::Base default_scope:order => 'title’ named_scope:published, :conditions => {:published => true} named_scope:unpublished, :conditions => {:published => false} end Rails3 class Post < ActiveRecord::Base default_scopeorder('title') 	scope :published, where(:published=> true)scope:unpublished, where(:published=> false) end
ActiveRelation – new finder methods where (:conditions) having (:conditions) select group order limit offset joins includes (:include) lock readonly from
ActiveModel Attribute methods Callbacks Dirty Errors Naming Observing Serialization Translation Validations
ActiveModel - example class Applicant include ActiveModel::Validationsvalidates_presence_of:name, :email attr_accessor:name, :email end
XSS
XSS Rails2 <%=@post.body %> <%= h@post.body %> Rails3 <%= raw @post.body %> <%= @post.body.html_safe %> <%= @post.body %>
Unobtrusive Javascript HTML 5 custom data attributes: data-* data-remote data-method data-confirm data-disable-with
Unobtrusive Javascript Rails2 <%= link_to_remote'Show', :url=> post %> <a href="#" onclick="new Ajax.Request('/posts/1', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('9sk..44d')}); return false;">Show</a> Rails3 <%= link_to'Show', post, :remote => true %> <a href="/posts/1" data-remote="true">Show</a>
Unobtrusive Javascript Rails2 <% remote_form_for(@post) do |f| %> <form action="/posts" class="new_post" id="new_post" method="post" onsubmit="new Ajax.Request('/posts', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;"> Rails3 <%= form_for(@post, :remote => true) do |f| %> <form action="/posts" class="new_post" data-remote="true" id="new_post" method="post">
Unobtrusive Javascript <%= link_to'Destroy', post, :confirm => 'Are you sure?', :method => :delete %> Rails2 <a href="/posts/1" onclick="if (confirm('Are you sure?')) { varf = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;varm = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);vars = document.createElement('input'); s.setAttribute ('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', '9skdJ0k+l9/ q3PWToz6MtfyiB2gcyhnKubeGV6WFL44='); f.appendChild(s);f.submit(); };return false;">Destroy</a> Rails3 <a href="/posts/1" data-method="delete" rel="nofollow">Destroy</a> <a href="/posts/1" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a>
Unobtrusive Javascript Rails2 <%= f.submit'Create Post', :disable_with=> "Please wait..." %> <input id="post_submit" name="commit" onclick="if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }else { hiddenCommit = document.createElement('input');hiddenCommit.type = 'hidden';hiddenCommit.value = this.value;hiddenCommit.name = this.name;this.form.appendChild(hiddenCommit); } this.setAttribute('originalValue', this.value);this.disabled = true;this.value='Please wait...';result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());if (result == false) { this.value = this.getAttribute ('originalValue');this.disabled = false; }return result;" type="submit" value="Create Post" /> Rails3 <%= f.submit:disable_with=> "Please wait..." %> <input data-disable-with="Please wait..." id="post_submit" name="commit" type="submit" value="Create Post" />
Unobtrusive Javascript Deprecated Methods: link_to_remote remote_form_for observe_field observe_form form_remote_tag button_to_remote submit_to_remote link_to_function periodically_call_remote
Links Rails Guides http://guides.rails.info/ Rails3 Ropes coursehttp://en.oreilly.com/rails2010/public/schedule/detail/14137 Reading Listhttp://mediumexposure.com/rails-3-reading-material/ Screencastshttp://rubyonrails.org/screencasts/rails3/

More Related Content

Viewers also liked

Viewers also liked (8)

E Business
E BusinessE Business
E Business
 
Materia
MateriaMateria
Materia
 
Senso Presentation
Senso PresentationSenso Presentation
Senso Presentation
 
Crm
CrmCrm
Crm
 
powerpoint
powerpointpowerpoint
powerpoint
 
Materia
MateriaMateria
Materia
 
Argument
ArgumentArgument
Argument
 
Using a mobile portal to monitor sap hana
Using a mobile portal to monitor sap hanaUsing a mobile portal to monitor sap hana
Using a mobile portal to monitor sap hana
 

Similar to Rails3 for Rails2 developers

Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful CodeGreggPollack
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
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
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Introzhang tao
 
Les nouveautés de Rails 3
Les nouveautés de Rails 3Les nouveautés de Rails 3
Les nouveautés de Rails 3LINAGORA
 
Introduction to Rails 3 - Anup Nivargi
Introduction to Rails 3 - Anup NivargiIntroduction to Rails 3 - Anup Nivargi
Introduction to Rails 3 - Anup NivargiPuneRailsMeetup
 
Intro to Rails 3 - Anup Nivargi
Intro to Rails 3 - Anup NivargiIntro to Rails 3 - Anup Nivargi
Intro to Rails 3 - Anup NivargiPuneRailsMeetup
 
Introduction to Rails 3
Introduction to Rails 3Introduction to Rails 3
Introduction to Rails 3Anup Nivargi
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Umair Amjad
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialYi-Ting Cheng
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsSagara Gunathunga
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails Mohit Jain
 
Model of the colossus @ Rupy Brazil 2013
Model of the colossus @ Rupy Brazil 2013 Model of the colossus @ Rupy Brazil 2013
Model of the colossus @ Rupy Brazil 2013 Mauro George
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 

Similar to Rails3 for Rails2 developers (20)

Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful Code
 
Rails3 changesets
Rails3 changesetsRails3 changesets
Rails3 changesets
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
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
 
Rails 4.0
Rails 4.0Rails 4.0
Rails 4.0
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
Les nouveautés de Rails 3
Les nouveautés de Rails 3Les nouveautés de Rails 3
Les nouveautés de Rails 3
 
Rails3 way
Rails3 wayRails3 way
Rails3 way
 
Introduction to Rails 3 - Anup Nivargi
Introduction to Rails 3 - Anup NivargiIntroduction to Rails 3 - Anup Nivargi
Introduction to Rails 3 - Anup Nivargi
 
Intro to Rails 3 - Anup Nivargi
Intro to Rails 3 - Anup NivargiIntro to Rails 3 - Anup Nivargi
Intro to Rails 3 - Anup Nivargi
 
Introduction to Rails 3
Introduction to Rails 3Introduction to Rails 3
Introduction to Rails 3
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3
 
Rail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendranRail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendran
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
 
Laravel
LaravelLaravel
Laravel
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
Model of the colossus @ Rupy Brazil 2013
Model of the colossus @ Rupy Brazil 2013 Model of the colossus @ Rupy Brazil 2013
Model of the colossus @ Rupy Brazil 2013
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 

Rails3 for Rails2 developers

  • 1. Rails 3 For Rails 2 Developers
  • 5. Creating a Rails 3 app rvmgemset create rails3 rvmgemset use rails3 gem install rails --pre rails new test_app
  • 7. Look at: environment.rb application.rb config.ru
  • 8. Routes - compatibility Old Style TestApp::Application.routes.drawdo |map| map.resources:posts do |post|post.resources:comments end end New Style TestApp::Application.routes.drawdo |map|resources:posts do resources :comments end end
  • 9. Routes - resources Old Style post.resources:comments, :member => { :preview => :post }, :collection => { :archived => :get } New Style resources :comments do post :preview, :on => :member get :archived, :on => :collection end
  • 10. Routes – named routes Old Style map.connect'login’, :controller => 'session', :action => 'new' map.login'login’, :controller => 'session', :action => 'new’ New Style match 'login' => 'session#new’ match 'login' => 'session#new', :as => :login
  • 11. Routes – root paths Old Style map.root:controller => 'users’, :action => 'index’ New Style root :to => 'users#index'
  • 12. Routes - Rack Endpoints get 'hello' => proc { |env| [200, {}, "Hello Rack"] } get 'rack_endpoint' => PostsController.action(:index) get 'rack_app' => CustomRackApp
  • 13. Routes Etc. Documentation here: http://guides.rails.info/routing.html
  • 14. ActionController – Legacy Style class UsersController< ApplicationController def index @users = User.all respond_todo |format| format.html format.xml{ render :xml => @users.to_xml} end end def show @user = User.find(params[:id]) respond_todo |format| format.html# show.html.erb format.xml{ render :xml => @user } end end end
  • 15. ActionController – New Style class UsersController< ApplicationControllerrespond_to:html, :xml, :json def index @users = User.all respond_with(@users) end def show @user = User.find(params[:id]) respond_with(@user) end end
  • 16. ActionMailer def welcome(user, subdomain) @user = user @subdomain= subdomain mail(:from=>admin@testapp.com, :to => user.email, :subject => "Welcome to TestApp") End UserMailer.welcome(user, subdomain).deliver
  • 17. ActionMailer class UserMailer< ActionMailer::Base default :from => "admin@testapp.com", :reply_to=> "noreply@testapp.com", "X-Time-Code" => Time.now.to_i.to_s def welcome(user, subdomain) @user = user @subdomain= subdomain attachments['test.pdf'] = File.read("#{Rails.root}/public/test.pdf") mail(:to=> @user.email, :subject => "Welcome to TestApp") do |format|format.html{ render 'other_html_welcome' } format.text{ render 'other_text_welcome' } end end end
  • 18. ActiveRelation Rails2 @posts = Post.find(:all, :conditions => {:published => true}) @posts = Post.find(:all, :conditions => {:author => "Joe"}, :includes => :comments, :order => "title", :limit => 10) Rails3 @posts = Post.where(:published=> true) @posts = Post.where(:author=> "Joe").include(:comments).order(:title).limit(10).all
  • 19. ActiveRelation - scopes Rails2 class Post < ActiveRecord::Base default_scope:order => 'title’ named_scope:published, :conditions => {:published => true} named_scope:unpublished, :conditions => {:published => false} end Rails3 class Post < ActiveRecord::Base default_scopeorder('title') scope :published, where(:published=> true)scope:unpublished, where(:published=> false) end
  • 20. ActiveRelation – new finder methods where (:conditions) having (:conditions) select group order limit offset joins includes (:include) lock readonly from
  • 21. ActiveModel Attribute methods Callbacks Dirty Errors Naming Observing Serialization Translation Validations
  • 22. ActiveModel - example class Applicant include ActiveModel::Validationsvalidates_presence_of:name, :email attr_accessor:name, :email end
  • 23. XSS
  • 24. XSS Rails2 <%=@post.body %> <%= h@post.body %> Rails3 <%= raw @post.body %> <%= @post.body.html_safe %> <%= @post.body %>
  • 25. Unobtrusive Javascript HTML 5 custom data attributes: data-* data-remote data-method data-confirm data-disable-with
  • 26. Unobtrusive Javascript Rails2 <%= link_to_remote'Show', :url=> post %> <a href="#" onclick="new Ajax.Request('/posts/1', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('9sk..44d')}); return false;">Show</a> Rails3 <%= link_to'Show', post, :remote => true %> <a href="/posts/1" data-remote="true">Show</a>
  • 27. Unobtrusive Javascript Rails2 <% remote_form_for(@post) do |f| %> <form action="/posts" class="new_post" id="new_post" method="post" onsubmit="new Ajax.Request('/posts', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;"> Rails3 <%= form_for(@post, :remote => true) do |f| %> <form action="/posts" class="new_post" data-remote="true" id="new_post" method="post">
  • 28. Unobtrusive Javascript <%= link_to'Destroy', post, :confirm => 'Are you sure?', :method => :delete %> Rails2 <a href="/posts/1" onclick="if (confirm('Are you sure?')) { varf = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;varm = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);vars = document.createElement('input'); s.setAttribute ('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', '9skdJ0k+l9/ q3PWToz6MtfyiB2gcyhnKubeGV6WFL44='); f.appendChild(s);f.submit(); };return false;">Destroy</a> Rails3 <a href="/posts/1" data-method="delete" rel="nofollow">Destroy</a> <a href="/posts/1" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a>
  • 29. Unobtrusive Javascript Rails2 <%= f.submit'Create Post', :disable_with=> "Please wait..." %> <input id="post_submit" name="commit" onclick="if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }else { hiddenCommit = document.createElement('input');hiddenCommit.type = 'hidden';hiddenCommit.value = this.value;hiddenCommit.name = this.name;this.form.appendChild(hiddenCommit); } this.setAttribute('originalValue', this.value);this.disabled = true;this.value='Please wait...';result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());if (result == false) { this.value = this.getAttribute ('originalValue');this.disabled = false; }return result;" type="submit" value="Create Post" /> Rails3 <%= f.submit:disable_with=> "Please wait..." %> <input data-disable-with="Please wait..." id="post_submit" name="commit" type="submit" value="Create Post" />
  • 30. Unobtrusive Javascript Deprecated Methods: link_to_remote remote_form_for observe_field observe_form form_remote_tag button_to_remote submit_to_remote link_to_function periodically_call_remote
  • 31. Links Rails Guides http://guides.rails.info/ Rails3 Ropes coursehttp://en.oreilly.com/rails2010/public/schedule/detail/14137 Reading Listhttp://mediumexposure.com/rails-3-reading-material/ Screencastshttp://rubyonrails.org/screencasts/rails3/

Editor's Notes

  1. Rails components decoupled from each otherEach component has a clear, published API.
  2. Action dispatch – new – handles: -Request handling and parameter parsing -Sessions, Rails’ flash, and cookie storage -File uploads -Routing, URL matching, and rescuing errors -HTTP conditional GETs -Client response and HTTP status code
  3. AbstractController Base: rendering, layouts, managing template pathsActionController Metal: exposes Rack endpointsActionController Base: like the rails2 one.
  4. If you’re mistakenly using rails2 – you’ll end up with an app called ‘new’.
  5. rake db:createrails srails g controller home indexrails g scaffold Post name:stringtitle:stringcontent:text
  6. environment.rb – much simplerapplication.rb – new!config.ru – yes, it’s a rack app
  7. Old style still works in rails3
  8. Makes named routes more obvious
  9. Rails 3 example from http://guides.rails.info/getting_started.html:root :to =&gt; &quot;home#index&quot;
  10. Still works – just ugly
  11. rails  g  mailer  UserMailer  welcome  forgot_passwordCreates user_mailer in app/mailers
  12. Rails2 find used to query the database.Rails3 returns an ActiveRecord::Relation – only queried when you do @posts.eachThe .all on the last query, forces the query to be evaluated, and so returns an array. Without it, you’d get an ActiveRelation object.
  13. First lines are unsafeSecond lines are safe