Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group December 2010

3,693 views

Published on

The third talk I gave in December in Milwaukee at Bucketworks. See my blog at blog.mattgauger.com for more info and full blog posts.

Published in: Technology
  • Be the first to comment

What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group December 2010

  1. 1. What’s new and great inRails 3
  2. 2. Don’t worry! All the links Text shown will bepresented at the end of the slides and on my blog.
  3. 3. There’s a lot to talk about, so
  4. 4. This is a longpresentation
  5. 5. I wanted to do something different thanlist the changes in Rails 3
  6. 6. Allow me to introduce you to someone.
  7. 7. This is Robin
  8. 8. “Robin would very much like to be akick-ass web developer, but has a hardtime keeping up with the buzzwords.” -- Flickr description
  9. 9. He’s a webdeveloper
  10. 10. He uses Rails 2.3 at his job,
  11. 11. where they make state-of-the-art TODO list web applications (and fight crime)
  12. 12. His boss
  13. 13. Batman
  14. 14. Wants the team to use Rails 3.
  15. 15. Because he heard itis the new hotness.
  16. 16. Batman tries to stay hip with the “web stuff”
  17. 17. Robin is already fairly familiar with Rails
  18. 18. In this case, he’s going to be starting from scratch
  19. 19. While it is possible to upgrade from Rails 2.x toRails 3, we’re not going to.
  20. 20. This is merely a learningexercise, so we’re skippingthe BDD/TDD for now, too.
  21. 21. Robin keeps up with a few Rails blogs,
  22. 22. And he’s read that rvmis what everyone is using
  23. 23. rvm is a way to install and use different versions ofRuby on the same machine
  24. 24. Robin uses Homebrewon his Mac, so he types:
  25. 25. $ brew install rvm
  26. 26. Sidenote:My recommendation would be to start with Cinderella if you’re on a Mac
  27. 27. What comes with Cinderella?
  28. 28. • mysql, postgres, redis, memcached andmongodb•ruby (1.8.7) with rails and sinatra viarvm gemsets. (& install Ruby 1.9 with rvm)•python (2.7) with pip.•node.js (0.2.0) with npm.•erlang (R13B04) environment.... and brew, and probably a lot more bynow.
  29. 29. With rvm, Robin can do this:
  30. 30. $ rvm install 1.9.2$ rvm use 1.9.2
  31. 31. $ rvm listrvm rubies ruby-1.8.7-p248 [ x86_64 ]=> ruby-1.9.2-p0 [ x86_64 ]
  32. 32. $ ruby -vruby 1.9.2p0 (2010-08-18 revision29036) [x86_64-darwin10.4.1]
  33. 33. So now Robin isrolling on Ruby 1.9.2
  34. 34. Next, he needs a gemset
  35. 35. A gemset is a collection ofgems, in this case that we’re associating with a project
  36. 36. Robin knows this comes in later, when he startsusing bundler in his app
  37. 37. $ rvm gemset create totodo$ rvm ruby-1.9.2-p0@totodo
  38. 38. Now any gems he installs will be on Ruby 1.9.2
  39. 39. And more importantly,will be kept with his app.
  40. 40. Robin installs Rails 3.0.3
  41. 41. $ gem install rails -v 3.0.3
  42. 42. And the Heroku gem
  43. 43. $ gem install heroku
  44. 44. He creates a new app called totodo (it’s a todo list!)
  45. 45. # Create a new Rails 3 app:$ rails new totodo$ cd totodo/
  46. 46. And grabs gems thatRails needs with Bundler
  47. 47. # Use Bundler to install gems:$ bundle install
  48. 48. Let’s look at Bundler
  49. 49. In Rails 2, Robinwould have to do this:
  50. 50. # Edit environment.rb:config.gem "haml"config.gem "sass"# Then do$ rake gems:install
  51. 51. In Rails 3 with Bundler:
  52. 52. # Edit the Gemfile:source "http://rubygems.org"gem "haml"gem "sass"# Then run:$ bundle install
  53. 53. We can also usegroups for gems:
  54. 54. # Gemfile:source "http://rubygems.org"gem "haml"gem "sass"group :test,:development do gem "webrat" gem "rspec"end# Then go run:$ bundle
  55. 55. Now webrat and rspec will be installed and used, butonly in the environments listed
  56. 56. Moving on, we setup git and heroku
  57. 57. # Set up git repo:$ git init .$ git add *$ git commit -m “Initial commit ofbare Rails 3 project.”# Create a new Heroku app:$ heroku create$ git push heroku master
  58. 58. Robin is all set to develop
  59. 59. He’s is looking at the files in his newly created project,
  60. 60. and noticing some differences
  61. 61. config/application.rb(replaces config/environment.rb)
  62. 62. require File.expand_path(../boot, __FILE__)require rails/all# If you have a Gemfile, require the gems listed there, including any gems# youve limited to :test, :development, or :production.Bundler.require(:default, Rails.env) if defined?(Bundler)module Totodo class Application < Rails::Application # [With a lot of comments cleaned up] # Configure generators values. config.generators do |g| g.orm :active_record g.template_engine :haml g.test_framework :rspec, :fixture => true end # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] endend
  63. 63. The important bit is
  64. 64. # Robin is going to use haml and rspec:# Configure generators values.config.generators do |g| g.orm :active_record g.template_engine :haml g.test_framework :rspecend
  65. 65. Next,
  66. 66. Robin needs a data model for what he’s storing
  67. 67. Which is a TODO list item
  68. 68. What makes up aTODO list item?
  69. 69. •ID•Title (Text)•Due Date (Datetime)•Is it done? (Boolean)
  70. 70. Robin wants to use $ script/generatewhich he comfortable with
  71. 71. But there isn’t ascript/generate in Rails 3
  72. 72. # Inside his totodo project folder:$ ls -al script/total 8drwxr-xr-x 3 robin staff 102 Dec 20 01:53 .drwxr-xr-x 21 robin staff 714 Dec 20 01:55 ..-rwxr-xr-x 1 robin staff 295 Dec 20 01:53 rails
  73. 73. Instead, everything goes through the rails script
  74. 74. # Remember doing these commands?$ script/generate something$ script/server$ script/console
  75. 75. # Replaced with:$ rails generate something$ rails g something #shorter form$ rails server$ rails s # shorter form$ rails console
  76. 76. What Robin wants is a scaffold
  77. 77. Again, he’s just learning Rails 3 here, so a scaffold will be fine.
  78. 78. $ rails generate scaffold Todo title:string due_date:datetime done:boolean
  79. 79. $ rails generate scaffold Todo title:string due_date:datetime done:boolean invoke active_record create db/migrate/20101220080933_create_todos.rb create app/models/todo.rb invoke test_unit create test/unit/todo_test.rb create test/fixtures/todos.yml route resources :todos invoke scaffold_controller create app/controllers/todos_controller.rb invoke erb create app/views/todos create app/views/todos/index.html.erb create app/views/todos/edit.html.erb create app/views/todos/show.html.erb create app/views/todos/new.html.erb create app/views/todos/_form.html.erb[and lots more output than this]
  80. 80. That’s a lot ofgenerated files
  81. 81. Robin wants to knowwhether migrations are different in Rails 3
  82. 82. So he looks in
  83. 83. db/migrate/20101220080933_create_todos.rb
  84. 84. class CreateTodos < ActiveRecord::Migration def self.up create_table :todos do |t| t.string :title t.datetime :due_date t.boolean :done t.timestamps end end def self.down drop_table :todos endend
  85. 85. That’s very similar towhat Robin is used to.
  86. 86. Robin runs the migration.
  87. 87. $ rake db:migrate(in /Users/robin/Projects/totodo)== CreateTodos: migrating ==================================-- create_table(:todos) -> 0.0019s== CreateTodos: migrated (0.0020s) =========================
  88. 88. Now, Robin wants to hook upthe routes to his new controller
  89. 89. He’s read that routes in Rails 3 are different,
  90. 90. but he hasn’t seen them yet
  91. 91. He’s pleased to findthat they’re simple:
  92. 92. # in config/routes.rb our scaffold placed:Totodo::Application.routes.draw do resources :todosend
  93. 93. Robin deletes thepublic/index.html file and maps the root path:
  94. 94. Totodo::Application.routes.draw do root :to => todos#index resources :todosend
  95. 95. And runs his dev server withthat nifty `rails s` command
  96. 96. Robin wants validations on his model
  97. 97. A ToDo list itemshould have a title
  98. 98. The syntax haschanged a little
  99. 99. class Todo < ActiveRecord::Base validates :title, :presence => trueend
  100. 100. Robin has a very,very basic app started
  101. 101. And a long way to go with Rails 3
  102. 102. Robin has a little bit oftime during his lunch break
  103. 103. So he reads up on the Merb project
  104. 104. 2006:The Merb project was started
  105. 105. At its start, Merb justserves ERb templates from Mongrel
  106. 106. Merb focuses on essentials
  107. 107. Componentmodularity
  108. 108. Extensible APIs
  109. 109. ORM/JS framework agnostic
  110. 110. December 2008:The Rails team announcesRoR and Merb will merge
  111. 111. Rails 3 is the result ofmerging Merb and RoR
  112. 112. And represents asignificant rewrite of most of Rails
  113. 113. Robin has stumbledonto a blog post by
  114. 114. Yehuda Katz
  115. 115. Summarizing theMerb+RoR merger back in 2008
  116. 116. Rails will become more modular
  117. 117. Rails will have better performance
  118. 118. Rails 3 will have a defined API, and atest suite for that API
  119. 119. Rails will allow things like DataMapper or Sequel to be first-class ORMs
  120. 120. Rails 3 will continue to embrace Rack
  121. 121. Reinvigorated, Robinjumps back into dev
  122. 122. As he begins to modifyhis controller, he runs into
  123. 123. ARel
  124. 124. (ActiveRelation)
  125. 125. Arel provides anSQL abstraction
  126. 126. Using relational algebra
  127. 127. Old and busted:
  128. 128. @users = User.find(:all, :conditions => {:approved => true})
  129. 129. New Hotness:
  130. 130. @users = User.where(:approved => true)
  131. 131. The Rails 2.x-style .find() method queries the DBimmediately and returns an array
  132. 132. The Arel-style .where() method returns anActiveRecord::Relation
  133. 133. What can we do with an ActiveRelation?
  134. 134. Add additionalparameters to the query
  135. 135. @users = User.where(:approved => true)# If a params[:order] was passed in,# add that condition to the query:@users = @users.order(params[:order])@users.each do |u| ...end
  136. 136. @users = User.where(:approved => true)# If a params[:order] was passed in,# add that condition to the query:@users = @users.order(params[:order])@users.each do |u| # Query runs here! ...end
  137. 137. We can even chain the last page of code together:
  138. 138. User.where(:approved => true).order(params[:order])
  139. 139. Rails 2:named_scope method
  140. 140. Rails 3:scope keyword
  141. 141. # Rails 2:class User < ActiveRecord::Base named_scope :approved, :conditions => {:approved => true}end# Rails 3:class User < ActiveRecord::Base scope :approved, where(:approved => true)end
  142. 142. There’s much, much more to Arel. Read the documentation.
  143. 143. Next up, Robin discovers that he can match any Rack app to a route
  144. 144. Totodo::Application.routes do match "/home", :to => HomeAppend
  145. 145. In fact, this is a lot likethe routes we saw earlier
  146. 146. Totodo::Application.routes.draw do root :to => todos#index match "/home", :to => HomeAppend
  147. 147. todos#indexhere is really a full fledgedRack application, too.
  148. 148. Routes are namespaced inside your app.
  149. 149. # Instead of:ActionController::Routing::Routes.draw do |map| map.resources :todosend# You do:Totodo::Application.routes do resources :todosend
  150. 150. The i18n gem brings in better i18n support, but Robin isn’tgoing to get into that right now.
  151. 151. How has ourController changed?
  152. 152. A simplified version of what our scaffold created would be:
  153. 153. class TodosController < ApplicationController respond_to :html, :xml, :js # GET /todos # GET /todos.xml def index respond_with(@todos = Todo.all) endend
  154. 154. As you can see, respond_to defines the formats the Controller responds to
  155. 155. And responds_with isthe data to send back
  156. 156. Our scaffold has alreadycreated the methods for our Todos controller
  157. 157. Robin pushes the app to Heroku
  158. 158. $ git push heroku master[... lots of output ...]-----> Launching... done http://deep-mountain-360.heroku.com/deployed to HerokuTo git@heroku.com:deep-mountain-360.git * [new branch] master -> master
  159. 159. Where can Robin go to learn more?
  160. 160. Robin can work through theRails Tutorial book for Rails 3: http://railstutorial.org/book
  161. 161. Which is a great resource. Highly recommended!
  162. 162. Robin is now equipped to fight crime, writeTODO lists, and learn more about Rails 3!
  163. 163. His boss wants to give him a little congrats
  164. 164. “POW”
  165. 165. Thank you!
  166. 166. See me after for free Github stickers :-)
  167. 167. Media used:http://www.flickr.com/photos/geirarne/43102913/(CC Attribution-NonCommercial-ShareAlike 2.0)http://www.flickr.com/photos/redraspus/2883658175(CC Attribution-NonCommercial-ShareAlike 2.0)http://www.flickr.com/photos/patolucas/2862975260/(CC Attribution-ShareAlike 2.0 Generic)
  168. 168. Links:https://github.com/atmos/cinderellahttp://rvm.beginrescueend.com/http://yehudakatz.com/2008/12/23/rails-and-merb-merge/http://railsforzombies.orghttp://railstutorial.org/bookhttp://rubyonrails.org/screencasts/rails3/https://github.com/brynary/arel

×