Slide 1

Slide 1 text

10 Things You Didn’t Know Rails Could Do

Slide 2

Slide 2 text

James Edward Gray II I am a regular on the Ruby Rogues podcast I have been a Rubyist for eight years now I have written a lot of documentation and code for Ruby, including CSV

Slide 3

Slide 3 text

10 Things You Didn’t Know Rails Could Do

Slide 4

Slide 4 text

10 Things You Didn’t Know Rails Could Do 4.2⨉ more awesome! 42

Slide 5

Slide 5 text

Rails 3.2.3 Can…

Slide 6

Slide 6 text

Get You a Hug, Every Friday 1 http://hugfriday.com/

Slide 7

Slide 7 text

Get You a Hug, Every Friday 1 http://hugfriday.com/

Slide 8

Slide 8 text

Get You a Hug, Every Friday 1 http://hugfriday.com/

Slide 9

Slide 9 text

Get You a Hug, Every Friday 1 http://hugfriday.com/

Slide 10

Slide 10 text

Get You a Hug, Every Friday 1 http://hugfriday.com/

Slide 11

Slide 11 text

Get You a Hug, Every Friday 1 http://hugfriday.com/

Slide 12

Slide 12 text

Get You a Hug, Every Friday 1 http://hugfriday.com/

Slide 13

Slide 13 text

Interfaces Ways to give Rails a hug

Slide 14

Slide 14 text

Run From a Single File From Avdi Grimm 2

Slide 15

Slide 15 text

Run From a Single File From Avdi Grimm 2

Slide 16

Slide 16 text

Run From a Single File From Avdi Grimm 2

Slide 17

Slide 17 text

Run From a Single File From Avdi Grimm 2

Slide 18

Slide 18 text

Run From a Single File From Avdi Grimm 2

Slide 19

Slide 19 text

Remind You of Things 3 class UsersController < ApplicationController # TODO: Make it possible to create new users. end

Slide 20

Slide 20 text

Remind You of Things 3 class UsersController < ApplicationController # TODO: Make it possible to create new users. end class User < ActiveRecord::Base # FIXME: Should token really be accessible? attr_accessible :bio, :email, :name, :token end

Slide 21

Slide 21 text

<%# OPTIMIZE: Paginate this listing. %> <%= render Article.all %> Remind You of Things 3 class UsersController < ApplicationController # TODO: Make it possible to create new users. end class User < ActiveRecord::Base # FIXME: Should token really be accessible? attr_accessible :bio, :email, :name, :token end

Slide 22

Slide 22 text

$ rake notes app/controllers/users_controller.rb: * [ 2] [TODO] Make it possible to create new users. app/models/user.rb: * [ 2] [FIXME] Should token really be accessible? app/views/articles/index.html.erb: * [ 1] [OPTIMIZE] Paginate this listing. <%# OPTIMIZE: Paginate this listing. %> <%= render Article.all %> Remind You of Things 3 class UsersController < ApplicationController # TODO: Make it possible to create new users. end class User < ActiveRecord::Base # FIXME: Should token really be accessible? attr_accessible :bio, :email, :name, :token end

Slide 23

Slide 23 text

$ rake notes app/controllers/users_controller.rb: * [ 2] [TODO] Make it possible to create new users. app/models/user.rb: * [ 2] [FIXME] Should token really be accessible? app/views/articles/index.html.erb: * [ 1] [OPTIMIZE] Paginate this listing. <%# OPTIMIZE: Paginate this listing. %> <%= render Article.all %> Remind You of Things 3 class UsersController < ApplicationController # TODO: Make it possible to create new users. end class User < ActiveRecord::Base # FIXME: Should token really be accessible? attr_accessible :bio, :email, :name, :token end

Slide 24

Slide 24 text

<%# OPTIMIZE: Paginate this listing. %> <%= render Article.all %> Remind You of Things 3 class UsersController < ApplicationController # TODO: Make it possible to create new users. end class User < ActiveRecord::Base # FIXME: Should token really be accessible? attr_accessible :bio, :email, :name, :token end $ rake notes:todo app/controllers/users_controller.rb: * [ 2] Make it possible to create new users. $ rake notes:fixme app/models/user.rb: * [ 2] Should token really be accessible?

Slide 25

Slide 25 text

<%# OPTIMIZE: Paginate this listing. %> <%= render Article.all %> Remind You of Things 3 class UsersController < ApplicationController # TODO: Make it possible to create new users. end class User < ActiveRecord::Base # FIXME: Should token really be accessible? attr_accessible :bio, :email, :name, :token end $ rake notes:todo app/controllers/users_controller.rb: * [ 2] Make it possible to create new users. $ rake notes:fixme app/models/user.rb: * [ 2] Should token really be accessible?

Slide 26

Slide 26 text

Remind You of Things 3 class Article < ActiveRecord::Base belongs_to :user attr_accessible :body, :subject # JEG2: Add that code from your blog here. end $ rake notes:custom ANNOTATION=JEG2 app/models/article.rb: * [ 4] Add that Code from your blog here.

Slide 27

Slide 27 text

Remind You of Things 3 class Article < ActiveRecord::Base belongs_to :user attr_accessible :body, :subject # JEG2: Add that code from your blog here. end $ rake notes:custom ANNOTATION=JEG2 app/models/article.rb: * [ 4] Add that Code from your blog here.

Slide 28

Slide 28 text

Remind You of Things 3

Slide 29

Slide 29 text

Sandbox Your Console 4 $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0] $ rails c --sandbox Loading development environment in sandbox (Rails 3.2.3) Any modifications you make will be rolled back on exit >> jeg2 = User.create!(name: "James Edward Gray II") => # >> article = Article.new(subject: "First Post").tap { |a| a.user = jeg2; a.save! } => # >> Comment.new(body: "I need to add this.").tap { |c| c.user, c.article = jeg2, article; c.save! } => # >> [Article, Comment, User].map(&:count) => [1, 1, 1] >> exit $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0]

Slide 30

Slide 30 text

Sandbox Your Console 4 $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0] $ rails c --sandbox Loading development environment in sandbox (Rails 3.2.3) Any modifications you make will be rolled back on exit >> jeg2 = User.create!(name: "James Edward Gray II") => # >> article = Article.new(subject: "First Post").tap { |a| a.user = jeg2; a.save! } => # >> Comment.new(body: "I need to add this.").tap { |c| c.user, c.article = jeg2, article; c.save! } => # >> [Article, Comment, User].map(&:count) => [1, 1, 1] >> exit $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0]

Slide 31

Slide 31 text

Sandbox Your Console 4 $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0] $ rails c --sandbox Loading development environment in sandbox (Rails 3.2.3) Any modifications you make will be rolled back on exit >> jeg2 = User.create!(name: "James Edward Gray II") => # >> article = Article.new(subject: "First Post").tap { |a| a.user = jeg2; a.save! } => # >> Comment.new(body: "I need to add this.").tap { |c| c.user, c.article = jeg2, article; c.save! } => # >> [Article, Comment, User].map(&:count) => [1, 1, 1] >> exit $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0]

Slide 32

Slide 32 text

Sandbox Your Console 4 $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0] $ rails c --sandbox Loading development environment in sandbox (Rails 3.2.3) Any modifications you make will be rolled back on exit >> jeg2 = User.create!(name: "James Edward Gray II") => # >> article = Article.new(subject: "First Post").tap { |a| a.user = jeg2; a.save! } => # >> Comment.new(body: "I need to add this.").tap { |c| c.user, c.article = jeg2, article; c.save! } => # >> [Article, Comment, User].map(&:count) => [1, 1, 1] >> exit $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0]

Slide 33

Slide 33 text

Sandbox Your Console 4 $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0] $ rails c --sandbox Loading development environment in sandbox (Rails 3.2.3) Any modifications you make will be rolled back on exit >> jeg2 = User.create!(name: "James Edward Gray II") => # >> article = Article.new(subject: "First Post").tap { |a| a.user = jeg2; a.save! } => # >> Comment.new(body: "I need to add this.").tap { |c| c.user, c.article = jeg2, article; c.save! } => # >> [Article, Comment, User].map(&:count) => [1, 1, 1] >> exit $ rails r 'p [Article, Comment, User].map(&:count)' [0, 0, 0]

Slide 34

Slide 34 text

Run Helper Methods in the Console 5 $ rails c Loading development environment (Rails 3.2.3) >> helper.number_to_currency(100) => "$100.00" >> helper.time_ago_in_words(3.days.ago) => "3 days"

Slide 35

Slide 35 text

Run Helper Methods in the Console 5 $ rails c Loading development environment (Rails 3.2.3) >> helper.number_to_currency(100) => "$100.00" >> helper.time_ago_in_words(3.days.ago) => "3 days"

Slide 36

Slide 36 text

Use Non-WEBrick Servers in Development 6 source 'https://rubygems.org' # ... group :development do gem "thin" end $ rails s thin => Booting Thin => Rails 3.2.3 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server >> Thin web server (v1.3.1 codename Triple Espresso) >> Maximum connections set to 1024 >> Listening on 0.0.0.0:3000, CTRL+C to stop

Slide 37

Slide 37 text

Use Non-WEBrick Servers in Development 6 source 'https://rubygems.org' # ... group :development do gem "thin" end $ rails s thin => Booting Thin => Rails 3.2.3 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server >> Thin web server (v1.3.1 codename Triple Espresso) >> Maximum connections set to 1024 >> Listening on 0.0.0.0:3000, CTRL+C to stop

Slide 38

Slide 38 text

Allow You to Tap Into its Configuration From Josh Susser 7 # lib/custom/railtie.rb module Custom class Railtie < Rails::Railtie config.custom = ActiveSupport::OrderedOptions.new end end

Slide 39

Slide 39 text

Allow You to Tap Into its Configuration From Josh Susser 7 # lib/custom/railtie.rb module Custom class Railtie < Rails::Railtie config.custom = ActiveSupport::OrderedOptions.new end end

Slide 40

Slide 40 text

Allow You to Tap Into its Configuration From Josh Susser 7 # lib/custom/railtie.rb module Custom class Railtie < Rails::Railtie config.custom = ActiveSupport::OrderedOptions.new end end # config/application.rb # ... require_relative "../lib/custom/railtie" module Blog class Application < Rails::Application # ... config.custom.setting = 42 end end

Slide 41

Slide 41 text

Allow You to Tap Into its Configuration From Josh Susser 7 # lib/custom/railtie.rb module Custom class Railtie < Rails::Railtie config.custom = ActiveSupport::OrderedOptions.new end end # config/application.rb # ... require_relative "../lib/custom/railtie" module Blog class Application < Rails::Application # ... config.custom.setting = 42 end end

Slide 42

Slide 42 text

Allow You to Tap Into its Configuration From Josh Susser 7 # lib/custom/railtie.rb module Custom class Railtie < Rails::Railtie config.custom = ActiveSupport::OrderedOptions.new end end # config/application.rb # ... require_relative "../lib/custom/railtie" module Blog class Application < Rails::Application # ... config.custom.setting = 42 end end

Slide 43

Slide 43 text

Keep You Entertained 8

Slide 44

Slide 44 text

Keep You Entertained 8

Slide 45

Slide 45 text

The Database A place to store all that drama

Slide 46

Slide 46 text

Understand Shorthand Migrations $ rails g resource user name:string email:string token:string bio:text 9 From José Valim

Slide 47

Slide 47 text

Understand Shorthand Migrations $ rails g resource user name:string email:string token:string bio:text $ rails g resource user name email token:string{6} bio:text 9 From José Valim

Slide 48

Slide 48 text

Understand Shorthand Migrations $ rails g resource user name:string email:string token:string bio:text $ rails g resource user name email token:string{6} bio:text class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :email t.string :token, :limit => 6 t.text :bio t.timestamps end end end 9 From José Valim

Slide 49

Slide 49 text

Understand Shorthand Migrations $ rails g resource user name:string email:string token:string bio:text $ rails g resource user name email token:string{6} bio:text class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :email t.string :token, :limit => 6 t.text :bio t.timestamps end end end 9 From José Valim

Slide 50

Slide 50 text

Understand Shorthand Migrations $ rails g resource user name:string email:string token:string bio:text $ rails g resource user name email token:string{6} bio:text class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :email t.string :token, :limit => 6 t.text :bio t.timestamps end end end 9 From José Valim

Slide 51

Slide 51 text

Add Indexes to Migrations $ rails g resource user name:index email:uniq token:string{6} bio:text 10 From José Valim

Slide 52

Slide 52 text

Add Indexes to Migrations $ rails g resource user name:index email:uniq token:string{6} bio:text class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :email t.string :token, :limit => 6 t.text :bio t.timestamps end add_index :users, :name add_index :users, :email, :unique => true end end 10 From José Valim

Slide 53

Slide 53 text

Add Indexes to Migrations $ rails g resource user name:index email:uniq token:string{6} bio:text class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :email t.string :token, :limit => 6 t.text :bio t.timestamps end add_index :users, :name add_index :users, :email, :unique => true end end 10 From José Valim

Slide 54

Slide 54 text

Add Indexes to Migrations $ rails g resource user name:index email:uniq token:string{6} bio:text class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :email t.string :token, :limit => 6 t.text :bio t.timestamps end add_index :users, :name add_index :users, :email, :unique => true end end 10 From José Valim

Slide 55

Slide 55 text

Add Associations to a Migration $ rails g resource article user:references subject body:text 11 From José Valim

Slide 56

Slide 56 text

Add Associations to a Migration $ rails g resource article user:references subject body:text class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.references :user t.string :subject t.text :body t.timestamps end add_index :articles, :user_id end end class Article < ActiveRecord::Base belongs_to :user attr_accessible :body, :subject end 11 From José Valim

Slide 57

Slide 57 text

Add Associations to a Migration $ rails g resource article user:references subject body:text class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.references :user t.string :subject t.text :body t.timestamps end add_index :articles, :user_id end end class Article < ActiveRecord::Base belongs_to :user attr_accessible :body, :subject end 11 From José Valim

Slide 58

Slide 58 text

Add Associations to a Migration $ rails g resource article user:references subject body:text class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.references :user t.string :subject t.text :body t.timestamps end add_index :articles, :user_id end end class Article < ActiveRecord::Base belongs_to :user attr_accessible :body, :subject end 11 From José Valim

Slide 59

Slide 59 text

Add Associations to a Migration $ rails g resource article user:references subject body:text class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.references :user t.string :subject t.text :body t.timestamps end add_index :articles, :user_id end end class Article < ActiveRecord::Base belongs_to :user attr_accessible :body, :subject end 11 From José Valim

Slide 60

Slide 60 text

Add Associations to a Migration $ rails g resource article user:references subject body:text class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.references :user t.string :subject t.text :body t.timestamps end add_index :articles, :user_id end end class Article < ActiveRecord::Base belongs_to :user attr_accessible :body, :subject end $ rails g resource comment user:belongs_to article:belongs_to body:text 11 From José Valim

Slide 61

Slide 61 text

Add Associations to a Migration $ rails g resource article user:references subject body:text class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.references :user t.string :subject t.text :body t.timestamps end add_index :articles, :user_id end end class Article < ActiveRecord::Base belongs_to :user attr_accessible :body, :subject end $ rails g resource comment user:belongs_to article:belongs_to body:text 11 From José Valim

Slide 62

Slide 62 text

Show You the Status of the Database $ rake db:migrate:status database: db/development.sqlite3 Status Migration ID Migration Name -------------------------------------------------- up 20120414155612 Create users up 20120414160528 Create articles down 20120414161355 Create comments 12

Slide 63

Slide 63 text

Show You the Status of the Database $ rake db:migrate:status database: db/development.sqlite3 Status Migration ID Migration Name -------------------------------------------------- up 20120414155612 Create users up 20120414160528 Create articles down 20120414161355 Create comments 12

Slide 64

Slide 64 text

Import Your CSV Data 13 Name,Email James,[email protected] Dana,[email protected] Summer,[email protected] require "csv" namespace :users do desc "Import users from a CSV file" task :import => :environment do path = ENV.fetch("CSV_FILE") { File.join(File.dirname(__FILE__), *%w[.. .. db data users.csv]) } CSV.foreach(path, headers: true, header_converters: :symbol) do |row| User.create(row.to_hash) end end end

Slide 65

Slide 65 text

Import Your CSV Data 13 Name,Email James,[email protected] Dana,[email protected] Summer,[email protected] require "csv" namespace :users do desc "Import users from a CSV file" task :import => :environment do path = ENV.fetch("CSV_FILE") { File.join(File.dirname(__FILE__), *%w[.. .. db data users.csv]) } CSV.foreach(path, headers: true, header_converters: :symbol) do |row| User.create(row.to_hash) end end end

Slide 66

Slide 66 text

Import Your CSV Data 13 Name,Email James,[email protected] Dana,[email protected] Summer,[email protected] require "csv" namespace :users do desc "Import users from a CSV file" task :import => :environment do path = ENV.fetch("CSV_FILE") { File.join(File.dirname(__FILE__), *%w[.. .. db data users.csv]) } CSV.foreach(path, headers: true, header_converters: :symbol) do |row| User.create(row.to_hash) end end end

Slide 67

Slide 67 text

Store CSV in Your Database 14 class Article < ActiveRecord::Base require "csv" module CSVSerializer module_function def load(field) field.to_s.parse_csv end def dump(object) Array(object).to_csv end end serialize :categories, CSVSerializer # ... attr_accessible :body, :subject, :categories end

Slide 68

Slide 68 text

Store CSV in Your Database 14 class Article < ActiveRecord::Base require "csv" module CSVSerializer module_function def load(field) field.to_s.parse_csv end def dump(object) Array(object).to_csv end end serialize :categories, CSVSerializer # ... attr_accessible :body, :subject, :categories end

Slide 69

Slide 69 text

Store CSV in Your Database 14 class Article < ActiveRecord::Base require "csv" module CSVSerializer module_function def load(field) field.to_s.parse_csv end def dump(object) Array(object).to_csv end end serialize :categories, CSVSerializer # ... attr_accessible :body, :subject, :categories end $ rails c Loading development environment (Rails 3.2.3) >> Article.create!(subject: "JEG2's Rails Hacks", categories: ["Rails", "Gray, James", "hacks"]) => # >> Article.last.categories => ["Rails", "Gray, James", "hacks"] >> exit $ sqlite3 db/development.sqlite3 'SELECT categories FROM articles ORDER BY created_at DESC LIMIT 1' -- Loading resources from /Users/james/.sqliterc categories -------------------------- Rails,"Gray, James",hacks

Slide 70

Slide 70 text

Store CSV in Your Database 14 class Article < ActiveRecord::Base require "csv" module CSVSerializer module_function def load(field) field.to_s.parse_csv end def dump(object) Array(object).to_csv end end serialize :categories, CSVSerializer # ... attr_accessible :body, :subject, :categories end $ rails c Loading development environment (Rails 3.2.3) >> Article.create!(subject: "JEG2's Rails Hacks", categories: ["Rails", "Gray, James", "hacks"]) => # >> Article.last.categories => ["Rails", "Gray, James", "hacks"] >> exit $ sqlite3 db/development.sqlite3 'SELECT categories FROM articles ORDER BY created_at DESC LIMIT 1' -- Loading resources from /Users/james/.sqliterc categories -------------------------- Rails,"Gray, James",hacks

Slide 71

Slide 71 text

Store CSV in Your Database 14 class Article < ActiveRecord::Base require "csv" module CSVSerializer module_function def load(field) field.to_s.parse_csv end def dump(object) Array(object).to_csv end end serialize :categories, CSVSerializer # ... attr_accessible :body, :subject, :categories end $ rails c Loading development environment (Rails 3.2.3) >> Article.create!(subject: "JEG2's Rails Hacks", categories: ["Rails", "Gray, James", "hacks"]) => # >> Article.last.categories => ["Rails", "Gray, James", "hacks"] >> exit $ sqlite3 db/development.sqlite3 'SELECT categories FROM articles ORDER BY created_at DESC LIMIT 1' -- Loading resources from /Users/james/.sqliterc categories -------------------------- Rails,"Gray, James",hacks

Slide 72

Slide 72 text

“Pluck” Fields Out of Your Database 15 From Ryan Bates $ rails c Loading development environment (Rails 3.2.3) >> User.select(:email).map(&:email) User Load (0.1ms) SELECT email FROM "users" => ["[email protected]", "[email protected]", "[email protected]"] >> User.pluck(:email) (0.2ms) SELECT email FROM "users" => ["[email protected]", "[email protected]", "[email protected]"] >> User.uniq.pluck(:email) (0.2ms) SELECT DISTINCT email FROM "users" => ["[email protected]", "[email protected]", "[email protected]"]

Slide 73

Slide 73 text

“Pluck” Fields Out of Your Database 15 From Ryan Bates $ rails c Loading development environment (Rails 3.2.3) >> User.select(:email).map(&:email) User Load (0.1ms) SELECT email FROM "users" => ["[email protected]", "[email protected]", "[email protected]"] >> User.pluck(:email) (0.2ms) SELECT email FROM "users" => ["[email protected]", "[email protected]", "[email protected]"] >> User.uniq.pluck(:email) (0.2ms) SELECT DISTINCT email FROM "users" => ["[email protected]", "[email protected]", "[email protected]"]

Slide 74

Slide 74 text

“Pluck” Fields Out of Your Database 15 From Ryan Bates $ rails c Loading development environment (Rails 3.2.3) >> User.select(:email).map(&:email) User Load (0.1ms) SELECT email FROM "users" => ["[email protected]", "[email protected]", "[email protected]"] >> User.pluck(:email) (0.2ms) SELECT email FROM "users" => ["[email protected]", "[email protected]", "[email protected]"] >> User.uniq.pluck(:email) (0.2ms) SELECT DISTINCT email FROM "users" => ["[email protected]", "[email protected]", "[email protected]"]

Slide 75

Slide 75 text

Count Records in Groups 16 $ rails g resource event article:belongs_to trigger

Slide 76

Slide 76 text

Count Records in Groups 16 $ rails g resource event article:belongs_to trigger $ rails c Loading development environment (Rails 3.2.3) >> article = Article.last => # >> {edit: 3, view: 10}.each do |trigger, count| ?> count.times do ?> Event.new(trigger: trigger).tap { |e| e.article = article; e.save! } >> end >> end => {:edit=>3, :view=>10} >> Event.count => 13 >> Event.group(:trigger).count => {"edit"=>3, "view"=>10}

Slide 77

Slide 77 text

Count Records in Groups 16 $ rails g resource event article:belongs_to trigger $ rails c Loading development environment (Rails 3.2.3) >> article = Article.last => # >> {edit: 3, view: 10}.each do |trigger, count| ?> count.times do ?> Event.new(trigger: trigger).tap { |e| e.article = article; e.save! } >> end >> end => {:edit=>3, :view=>10} >> Event.count => 13 >> Event.group(:trigger).count => {"edit"=>3, "view"=>10}

Slide 78

Slide 78 text

Count Records in Groups 16 $ rails g resource event article:belongs_to trigger $ rails c Loading development environment (Rails 3.2.3) >> article = Article.last => # >> {edit: 3, view: 10}.each do |trigger, count| ?> count.times do ?> Event.new(trigger: trigger).tap { |e| e.article = article; e.save! } >> end >> end => {:edit=>3, :view=>10} >> Event.count => 13 >> Event.group(:trigger).count => {"edit"=>3, "view"=>10}

Slide 79

Slide 79 text

Allow You to Override Associations 17 From Josh Susser class Car < ActiveRecord::Base belongs_to :owner belongs_to :previous_owner, class_name: "Owner" def owner=(new_owner) self.previous_owner = owner super end end

Slide 80

Slide 80 text

Allow You to Override Associations 17 From Josh Susser class Car < ActiveRecord::Base belongs_to :owner belongs_to :previous_owner, class_name: "Owner" def owner=(new_owner) self.previous_owner = owner super end end

Slide 81

Slide 81 text

Instantiate Records Without a Database 18 $ rails c Loading development environment (Rails 3.2.3) >> User.find(1) => # >> jeg2 = User.instantiate("id" => 1, "email" => "[email protected]") => # >> jeg2.name = "James Edward Gray II" => "James Edward Gray II" >> jeg2.save! => true >> User.find(1) => #

Slide 82

Slide 82 text

Instantiate Records Without a Database 18 $ rails c Loading development environment (Rails 3.2.3) >> User.find(1) => # >> jeg2 = User.instantiate("id" => 1, "email" => "[email protected]") => # >> jeg2.name = "James Edward Gray II" => "James Edward Gray II" >> jeg2.save! => true >> User.find(1) => #

Slide 83

Slide 83 text

Instantiate Records Without a Database 18 $ rails c Loading development environment (Rails 3.2.3) >> User.find(1) => # >> jeg2 = User.instantiate("id" => 1, "email" => "[email protected]") => # >> jeg2.name = "James Edward Gray II" => "James Edward Gray II" >> jeg2.save! => true >> User.find(1) => #

Slide 84

Slide 84 text

Use Limitless Strings in PostgreSQL 19 From Josh Susser $ rails g resource user bio # ... module PsqlApp class Application < Rails::Application # ... # Switch to limitless strings initializer "postgresql.no_default_string_limit" do ActiveSupport.on_load(:active_record) do adapter = ActiveRecord::ConnectionAdapters::PostgreSQLAdapter adapter::NATIVE_DATABASE_TYPES[:string].delete(:limit) end end end end

Slide 85

Slide 85 text

Use Limitless Strings in PostgreSQL 19 From Josh Susser $ rails g resource user bio $ rails c Loading development environment (Rails 3.2.3) >> very_long_bio = "X" * 10_000; :set => :set >> User.create!(bio: very_long_bio) => # >> User.last.bio.size => 10000

Slide 86

Slide 86 text

Use Limitless Strings in PostgreSQL 19 From Josh Susser $ rails g resource user bio $ rails c Loading development environment (Rails 3.2.3) >> very_long_bio = "X" * 10_000; :set => :set >> User.create!(bio: very_long_bio) => # >> User.last.bio.size => 10000

Slide 87

Slide 87 text

Use Full Text Search in PostgreSQL 20 $ rails g resource article subject body:text From PeepCode

Slide 88

Slide 88 text

Use Full Text Search in PostgreSQL 20 class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.string :subject t.text :body t.column :search, "tsvector" t.timestamps end execute <<-END_SQL CREATE INDEX articles_search_index ON articles USING gin(search); CREATE TRIGGER articles_search_update BEFORE INSERT OR UPDATE ON articles FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger( search, 'pg_catalog.english', subject, body ); END_SQL end end From PeepCode

Slide 89

Slide 89 text

Use Full Text Search in PostgreSQL 20 class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.string :subject t.text :body t.column :search, "tsvector" t.timestamps end execute <<-END_SQL CREATE INDEX articles_search_index ON articles USING gin(search); CREATE TRIGGER articles_search_update BEFORE INSERT OR UPDATE ON articles FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger( search, 'pg_catalog.english', subject, body ); END_SQL end end From PeepCode

Slide 90

Slide 90 text

Use Full Text Search in PostgreSQL 20 class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.string :subject t.text :body t.column :search, "tsvector" t.timestamps end execute <<-END_SQL CREATE INDEX articles_search_index ON articles USING gin(search); CREATE TRIGGER articles_search_update BEFORE INSERT OR UPDATE ON articles FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger( search, 'pg_catalog.english', subject, body ); END_SQL end end From PeepCode

Slide 91

Slide 91 text

Use Full Text Search in PostgreSQL 20 class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.string :subject t.text :body t.column :search, "tsvector" t.timestamps end execute <<-END_SQL CREATE INDEX articles_search_index ON articles USING gin(search); CREATE TRIGGER articles_search_update BEFORE INSERT OR UPDATE ON articles FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger( search, 'pg_catalog.english', subject, body ); END_SQL end end From PeepCode

Slide 92

Slide 92 text

Use Full Text Search in PostgreSQL 20 From PeepCode class Article < ActiveRecord::Base attr_accessible :body, :subject def self.search(query) sql = sanitize_sql_array(["plainto_tsquery('english', ?)", query]) where( "search @@ #{sql}" ).order( "ts_rank_cd(search, #{sql}) DESC" ) end end

Slide 93

Slide 93 text

Use Full Text Search in PostgreSQL 20 From PeepCode class Article < ActiveRecord::Base attr_accessible :body, :subject def self.search(query) sql = sanitize_sql_array(["plainto_tsquery('english', ?)", query]) where( "search @@ #{sql}" ).order( "ts_rank_cd(search, #{sql}) DESC" ) end end

Slide 94

Slide 94 text

Use Full Text Search in PostgreSQL 20 From PeepCode $ rails c Loading development environment (Rails 3.2.3) >> Article.create!(subject: "Full Text Search") => # >> Article.create!(body: "A stemmed search.") => # >> Article.create!(body: "You won't find me!") => # >> Article.search("search").map { |a| a.subject || a.body } => ["Full Text Search", "A stemmed search."] >> Article.search("stemming").map { |a| a.subject || a.body } => ["A stemmed search."]

Slide 95

Slide 95 text

Use Full Text Search in PostgreSQL 20 From PeepCode $ rails c Loading development environment (Rails 3.2.3) >> Article.create!(subject: "Full Text Search") => # >> Article.create!(body: "A stemmed search.") => # >> Article.create!(body: "You won't find me!") => # >> Article.search("search").map { |a| a.subject || a.body } => ["Full Text Search", "A stemmed search."] >> Article.search("stemming").map { |a| a.subject || a.body } => ["A stemmed search."]

Slide 96

Slide 96 text

Use Full Text Search in PostgreSQL 20 From PeepCode $ rails c Loading development environment (Rails 3.2.3) >> Article.create!(subject: "Full Text Search") => # >> Article.create!(body: "A stemmed search.") => # >> Article.create!(body: "You won't find me!") => # >> Article.search("search").map { |a| a.subject || a.body } => ["Full Text Search", "A stemmed search."] >> Article.search("stemming").map { |a| a.subject || a.body } => ["A stemmed search."]

Slide 97

Slide 97 text

Use Different a Database for Each User 21 def connect_to_user_database(name) config = ActiveRecord::Base.configurations["development"] .merge("database" => "db/#{name}.sqlite3") ActiveRecord::Base.establish_connection(config) end

Slide 98

Slide 98 text

Use Different a Database for Each User 21 def connect_to_user_database(name) config = ActiveRecord::Base.configurations["development"] .merge("database" => "db/#{name}.sqlite3") ActiveRecord::Base.establish_connection(config) end

Slide 99

Slide 99 text

Use Different a Database for Each User 21 def connect_to_user_database(name) config = ActiveRecord::Base.configurations["development"] .merge("database" => "db/#{name}.sqlite3") ActiveRecord::Base.establish_connection(config) end

Slide 100

Slide 100 text

Use Different a Database for Each User 21 def connect_to_user_database(name) config = ActiveRecord::Base.configurations["development"] .merge("database" => "db/#{name}.sqlite3") ActiveRecord::Base.establish_connection(config) end require "user_database"

Slide 101

Slide 101 text

Use Different a Database for Each User 21 namespace :db do desc "Add a new user database" task :add => %w[environment load_config] do name = ENV.fetch("DB_NAME") { fail "DB_NAME is required" } connect_to_user_database(name) ActiveRecord::Base.connection end namespace :migrate do desc "Migrate all user databases" task :all => %w[environment load_config] do ActiveRecord::Migration.verbose = ENV.fetch("VERBOSE", "true") == "true" Dir.glob("db/*.sqlite3") do |file| next if file == "db/test.sqlite3" connect_to_user_database(File.basename(file, ".sqlite3")) ActiveRecord::Migrator.migrate( ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] && ENV["VERSION"].to_i ) do |migration| ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope) end end end end end

Slide 102

Slide 102 text

Use Different a Database for Each User 21 namespace :db do desc "Add a new user database" task :add => %w[environment load_config] do name = ENV.fetch("DB_NAME") { fail "DB_NAME is required" } connect_to_user_database(name) ActiveRecord::Base.connection end namespace :migrate do desc "Migrate all user databases" task :all => %w[environment load_config] do ActiveRecord::Migration.verbose = ENV.fetch("VERBOSE", "true") == "true" Dir.glob("db/*.sqlite3") do |file| next if file == "db/test.sqlite3" connect_to_user_database(File.basename(file, ".sqlite3")) ActiveRecord::Migrator.migrate( ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] && ENV["VERSION"].to_i ) do |migration| ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope) end end end end end

Slide 103

Slide 103 text

Use Different a Database for Each User 21 $ rails g resource user name $ rake db:add DB_NAME=ruby_rogues $ rake db:add DB_NAME=grays $ rake db:migrate:all == CreateUsers: migrating ================================== -- create_table(:users) -> 0.0008s == CreateUsers: migrated (0.0008s) ========================= == CreateUsers: migrating ================================== -- create_table(:users) -> 0.0007s == CreateUsers: migrated (0.0008s) =========================

Slide 104

Slide 104 text

Use Different a Database for Each User 21 $ rails g resource user name $ rake db:add DB_NAME=ruby_rogues $ rake db:add DB_NAME=grays $ rake db:migrate:all == CreateUsers: migrating ================================== -- create_table(:users) -> 0.0008s == CreateUsers: migrated (0.0008s) ========================= == CreateUsers: migrating ================================== -- create_table(:users) -> 0.0007s == CreateUsers: migrated (0.0008s) =========================

Slide 105

Slide 105 text

Use Different a Database for Each User 21 $ rails g resource user name $ rake db:add DB_NAME=ruby_rogues $ rake db:add DB_NAME=grays $ rake db:migrate:all == CreateUsers: migrating ================================== -- create_table(:users) -> 0.0008s == CreateUsers: migrated (0.0008s) ========================= == CreateUsers: migrating ================================== -- create_table(:users) -> 0.0007s == CreateUsers: migrated (0.0008s) =========================

Slide 106

Slide 106 text

Use Different a Database for Each User 21 $ rails c >> connect_to_user_database("ruby_rogues") => # >> User.create!(name: "Chuck") => # >> User.create!(name: "Josh") => # >> User.create!(name: "Avdi") => # … >> connect_to_user_database("grays") => # >> User.create!(name: "James") => # >> User.create!(name: "Dana") => # >> User.create!(name: "Summer") => #

Slide 107

Slide 107 text

Use Different a Database for Each User 21 $ rails c >> connect_to_user_database("ruby_rogues") => # >> User.create!(name: "Chuck") => # >> User.create!(name: "Josh") => # >> User.create!(name: "Avdi") => # … >> connect_to_user_database("grays") => # >> User.create!(name: "James") => # >> User.create!(name: "Dana") => # >> User.create!(name: "Summer") => #

Slide 108

Slide 108 text

Use Different a Database for Each User 21 $ rails c >> connect_to_user_database("ruby_rogues") => # >> User.create!(name: "Chuck") => # >> User.create!(name: "Josh") => # >> User.create!(name: "Avdi") => # … >> connect_to_user_database("grays") => # >> User.create!(name: "James") => # >> User.create!(name: "Dana") => # >> User.create!(name: "Summer") => #

Slide 109

Slide 109 text

Use Different a Database for Each User 21 class ApplicationController < ActionController::Base protect_from_forgery before_filter :connect_to_database private def connect_to_database connect_to_user_database(request.subdomains.first) end end

Slide 110

Slide 110 text

Use Different a Database for Each User 21 class ApplicationController < ActionController::Base protect_from_forgery before_filter :connect_to_database private def connect_to_database connect_to_user_database(request.subdomains.first) end end

Slide 111

Slide 111 text

Use Different a Database for Each User 21

Slide 112

Slide 112 text

Use Different a Database for Each User 21

Slide 113

Slide 113 text

Intermission Am I going to make it???

Slide 114

Slide 114 text

Why Do This? I’m trying to give you new ideas Studies show this will help you solve Rails problems Also, it’s fun! Remember to have fun

Slide 115

Slide 115 text

Less Talk, More Tricks!!!

Slide 116

Slide 116 text

Refine Your Fashion Sense http://www.flickr.com/photos/oreillyconf/5735037920/ 22

Slide 117

Slide 117 text

Refine Your Fashion Sense http://www.flickr.com/photos/oreillyconf/5735037920/ http://www.flickr.com/photos/oreillyconf/5735038376/ 22

Slide 118

Slide 118 text

Refine Your Fashion Sense http://www.flickr.com/photos/oreillyconf/5735037920/ http://www.flickr.com/photos/oreillyconf/5735038376/ http://www.flickr.com/photos/aaronp/4609780419/ 22

Slide 119

Slide 119 text

Ruby Extensions Updating Ruby’s fashion sense

Slide 120

Slide 120 text

Write Files Atomically 23 class Comment < ActiveRecord::Base # ... Q_DIR = (Rails.root + "comment_queue").tap(&:mkpath) after_save :queue_comment def queue_comment File.atomic_write(Q_DIR + "#{id}.txt") do |f| f.puts "Article: #{article.subject}" f.puts "User: #{user.name}" f.puts body end end end

Slide 121

Slide 121 text

Write Files Atomically 23 class Comment < ActiveRecord::Base # ... Q_DIR = (Rails.root + "comment_queue").tap(&:mkpath) after_save :queue_comment def queue_comment File.atomic_write(Q_DIR + "#{id}.txt") do |f| f.puts "Article: #{article.subject}" f.puts "User: #{user.name}" f.puts body end end end

Slide 122

Slide 122 text

Write Files Atomically 23 $ ls comment_queue ls: comment_queue: No such file or directory $ rails r 'Comment.new(body: "Queue me.").tap { |c| c.article, c.user = Article.first, User.first; c.save! }' $ ls comment_queue 1.txt $ cat comment_queue/1.txt Article: JEG2's Rails Hacks User: James Edward Gray II Queue me.

Slide 123

Slide 123 text

Write Files Atomically 23 $ ls comment_queue ls: comment_queue: No such file or directory $ rails r 'Comment.new(body: "Queue me.").tap { |c| c.article, c.user = Article.first, User.first; c.save! }' $ ls comment_queue 1.txt $ cat comment_queue/1.txt Article: JEG2's Rails Hacks User: James Edward Gray II Queue me.

Slide 124

Slide 124 text

Merge Nested Hashes 24 $ rails c Loading development environment (Rails 3.2.3) >> {nested: {one: 1}}.merge(nested: {two: 2}) => {:nested=>{:two=>2}} >> {nested: {one: 1}}.deep_merge(nested: {two: 2}) => {:nested=>{:one=>1, :two=>2}}

Slide 125

Slide 125 text

Merge Nested Hashes 24 $ rails c Loading development environment (Rails 3.2.3) >> {nested: {one: 1}}.merge(nested: {two: 2}) => {:nested=>{:two=>2}} >> {nested: {one: 1}}.deep_merge(nested: {two: 2}) => {:nested=>{:one=>1, :two=>2}}

Slide 126

Slide 126 text

Remove Specific Keys From a Hash 25 $ rails c Loading development environment (Rails 3.2.3) >> params = {controller: "home", action: "index", from: "Google"} => {:controller=>"home", :action=>"index", :from=>"Google"} >> params.except(:controller, :action) => {:from=>"Google"}

Slide 127

Slide 127 text

Remove Specific Keys From a Hash 25 $ rails c Loading development environment (Rails 3.2.3) >> params = {controller: "home", action: "index", from: "Google"} => {:controller=>"home", :action=>"index", :from=>"Google"} >> params.except(:controller, :action) => {:from=>"Google"}

Slide 128

Slide 128 text

Add Defaults to Hash 26 $ rails c Loading development environment (Rails 3.2.3) >> {required: true}.merge(optional: true) => {:required=>true, :optional=>true} >> {required: true}.reverse_merge(optional: true) => {:optional=>true, :required=>true} >> {required: true, optional: false}.merge(optional: true) => {:required=>true, :optional=>true} >> {required: true, optional: false}.reverse_merge(optional: true) => {:optional=>false, :required=>true}

Slide 129

Slide 129 text

Add Defaults to Hash 26 $ rails c Loading development environment (Rails 3.2.3) >> {required: true}.merge(optional: true) => {:required=>true, :optional=>true} >> {required: true}.reverse_merge(optional: true) => {:optional=>true, :required=>true} >> {required: true, optional: false}.merge(optional: true) => {:required=>true, :optional=>true} >> {required: true, optional: false}.reverse_merge(optional: true) => {:optional=>false, :required=>true}

Slide 130

Slide 130 text

Add Defaults to Hash 26 $ rails c Loading development environment (Rails 3.2.3) >> {required: true}.merge(optional: true) => {:required=>true, :optional=>true} >> {required: true}.reverse_merge(optional: true) => {:optional=>true, :required=>true} >> {required: true, optional: false}.merge(optional: true) => {:required=>true, :optional=>true} >> {required: true, optional: false}.reverse_merge(optional: true) => {:optional=>false, :required=>true}

Slide 131

Slide 131 text

Add Defaults to Hash 26 $ rails c Loading development environment (Rails 3.2.3) >> {required: true}.merge(optional: true) => {:required=>true, :optional=>true} >> {required: true}.reverse_merge(optional: true) => {:optional=>true, :required=>true} >> {required: true, optional: false}.merge(optional: true) => {:required=>true, :optional=>true} >> {required: true, optional: false}.reverse_merge(optional: true) => {:optional=>false, :required=>true}

Slide 132

Slide 132 text

Answer Questions About Strings 27 $ rails g migration add_status_to_articles status

Slide 133

Slide 133 text

Answer Questions About Strings 27 $ rails g migration add_status_to_articles status class AddStatusToArticles < ActiveRecord::Migration def change add_column :articles, :status, :string, default: "Draft", null: false end end

Slide 134

Slide 134 text

Answer Questions About Strings 27 $ rails g migration add_status_to_articles status class AddStatusToArticles < ActiveRecord::Migration def change add_column :articles, :status, :string, default: "Draft", null: false end end

Slide 135

Slide 135 text

Answer Questions About Strings 27 $ rails c Loading development environment (Rails 3.2.3) >> env = Rails.env => "development" >> env.development? => true >> env.test? => false >> "magic".inquiry.magic? => true >> article = Article.first => # >> article.draft? => true >> article.published? => false

Slide 136

Slide 136 text

Answer Questions About Strings 27 $ rails c Loading development environment (Rails 3.2.3) >> env = Rails.env => "development" >> env.development? => true >> env.test? => false >> "magic".inquiry.magic? => true >> article = Article.first => # >> article.draft? => true >> article.published? => false

Slide 137

Slide 137 text

Answer Questions About Strings 27 $ rails c Loading development environment (Rails 3.2.3) >> env = Rails.env => "development" >> env.development? => true >> env.test? => false >> "magic".inquiry.magic? => true >> article = Article.first => # >> article.draft? => true >> article.published? => false

Slide 138

Slide 138 text

Answer Questions About Strings 27 $ rails c Loading development environment (Rails 3.2.3) >> env = Rails.env => "development" >> env.development? => true >> env.test? => false >> "magic".inquiry.magic? => true >> article = Article.first => # >> article.draft? => true >> article.published? => false

Slide 139

Slide 139 text

Answer Questions About Strings 27 class Article < ActiveRecord::Base # ... STATUSES = %w[Draft Published] validates_inclusion_of :status, in: STATUSES def method_missing(method, *args, &block) if method =~ /\A#{STATUSES.map(&:downcase).join("|")}\?\z/ status.downcase.inquiry.send(method) else super end end end

Slide 140

Slide 140 text

Answer Questions About Strings 27 class Article < ActiveRecord::Base # ... STATUSES = %w[Draft Published] validates_inclusion_of :status, in: STATUSES def method_missing(method, *args, &block) if method =~ /\A#{STATUSES.map(&:downcase).join("|")}\?\z/ status.downcase.inquiry.send(method) else super end end end

Slide 141

Slide 141 text

Answer Questions About Strings 27 class Article < ActiveRecord::Base # ... STATUSES = %w[Draft Published] validates_inclusion_of :status, in: STATUSES def method_missing(method, *args, &block) if method =~ /\A#{STATUSES.map(&:downcase).join("|")}\?\z/ status.downcase.inquiry.send(method) else super end end end

Slide 142

Slide 142 text

Get you on the cover of a magazine The hairdo may be required http://www.rubyinside.com/rubys-popularity-scales-new-heights-19.html 28

Slide 143

Slide 143 text

Get you voted “Hottest Hacker” http://pageman.multiply.com/links/item/21/David_Heinemeier_Hanssons_Blog 29

Slide 144

Slide 144 text

Get you voted “Hottest Hacker” http://pageman.multiply.com/links/item/21/David_Heinemeier_Hanssons_Blog 29

Slide 145

Slide 145 text

Get you voted “Hottest Hacker” http://pageman.multiply.com/links/item/21/David_Heinemeier_Hanssons_Blog http://torrentfreak.com/richard-stallman-opts-to-disobey-anti-piracy-law-110610/ 29

Slide 146

Slide 146 text

Views It’s all about how we look

Slide 147

Slide 147 text

Hide Comments From Your Users 30 <%# ERb comments do not %>

Home Page

From The Rails View

Slide 148

Slide 148 text

Hide Comments From Your Users 30 <%# ERb comments do not %>

Home Page

From The Rails View

Slide 149

Slide 149 text

Hide Comments From Your Users 30 <%# ERb comments do not %>

Home Page

Home Page

From The Rails View

Slide 150

Slide 150 text

Understand a Shorter ERb Syntax 31 # ... module Blog class Application < Rails::Application # ... # Broken: config.action_view.erb_trim_mode = '%' ActionView::Template::Handlers::ERB.erb_implementation = Class.new(ActionView::Template::Handlers::Erubis) do include ::Erubis::PercentLineEnhancer end end end % if current_user.try(:admin?) <%= render "edit_links" %> % end

Slide 151

Slide 151 text

Understand a Shorter ERb Syntax 31 # ... module Blog class Application < Rails::Application # ... # Broken: config.action_view.erb_trim_mode = '%' ActionView::Template::Handlers::ERB.erb_implementation = Class.new(ActionView::Template::Handlers::Erubis) do include ::Erubis::PercentLineEnhancer end end end % if current_user.try(:admin?) <%= render "edit_links" %> % end

Slide 152

Slide 152 text

Understand a Shorter ERb Syntax 31 # ... module Blog class Application < Rails::Application # ... # Broken: config.action_view.erb_trim_mode = '%' ActionView::Template::Handlers::ERB.erb_implementation = Class.new(ActionView::Template::Handlers::Erubis) do include ::Erubis::PercentLineEnhancer end end end % if current_user.try(:admin?) <%= render "edit_links" %> % end

Slide 153

Slide 153 text

Understand a Shorter ERb Syntax 31 # ... module Blog class Application < Rails::Application # ... # Broken: config.action_view.erb_trim_mode = '%' ActionView::Template::Handlers::ERB.erb_implementation = Class.new(ActionView::Template::Handlers::Erubis) do include ::Erubis::PercentLineEnhancer end end end % if current_user.try(:admin?) <%= render "edit_links" %> % end

Slide 154

Slide 154 text

Use Blocks to Avoid Assignments in Views 32 <% @cart.products.each do |product| %> <%= product.name %> <%= number_to_currency product.price %> <% end %> Subtotal <%= number_to_currency @cart.total %> Tax <%= number_to_currency(tax = calculate_tax(@cart.total)) %> Total <%= number_to_currency(@cart.total + tax) %> From The Rails View

Slide 155

Slide 155 text

Use Blocks to Avoid Assignments in Views 32 <% @cart.products.each do |product| %> <%= product.name %> <%= number_to_currency product.price %> <% end %> Subtotal <%= number_to_currency @cart.total %> Tax <%= number_to_currency(tax = calculate_tax(@cart.total)) %> Total <%= number_to_currency(@cart.total + tax) %> From The Rails View

Slide 156

Slide 156 text

Use Blocks to Avoid Assignments in Views 32 <% @cart.products.each do |product| %> <%= product.name %> <%= number_to_currency product.price %> <% end %> Subtotal <%= number_to_currency @cart.total %> Tax <%= number_to_currency(tax = calculate_tax(@cart.total)) %> Total <%= number_to_currency(@cart.total + tax) %> From The Rails View

Slide 157

Slide 157 text

<% @cart.products.each do |product| %> <%= product.name %> <%= number_to_currency product.price %> <% end %> Subtotal <%= number_to_currency @cart.total %> <% calculate_tax @cart.total do |tax| %> Tax <%= number_to_currency tax %> Total <%= number_to_currency(@cart.total + tax) %> <% end %> Use Blocks to Avoid Assignments in Views 32 From The Rails View

Slide 158

Slide 158 text

<% @cart.products.each do |product| %> <%= product.name %> <%= number_to_currency product.price %> <% end %> Subtotal <%= number_to_currency @cart.total %> <% calculate_tax @cart.total do |tax| %> Tax <%= number_to_currency tax %> Total <%= number_to_currency(@cart.total + tax) %> <% end %> Use Blocks to Avoid Assignments in Views 32 From The Rails View

Slide 159

Slide 159 text

Use Blocks to Avoid Assignments in Views 32 module CartHelper def calculate_tax(total, user = current_user) tax = TaxTable.for(user).calculate(total) if block_given? yield tax else tax end end end From The Rails View

Slide 160

Slide 160 text

Use Blocks to Avoid Assignments in Views 32 module CartHelper def calculate_tax(total, user = current_user) tax = TaxTable.for(user).calculate(total) if block_given? yield tax else tax end end end From The Rails View

Slide 161

Slide 161 text

Generate Multiple Tags at Once 33 From José Valim

Articles

<% @articles.each do |article| %> <%= content_tag_for(:div, article) do %>

<%= article.subject %>

<% end %> <% end %>

Slide 162

Slide 162 text

Generate Multiple Tags at Once 33 From José Valim

Articles

<% @articles.each do |article| %> <%= content_tag_for(:div, article) do %>

<%= article.subject %>

<% end %> <% end %>

Slide 163

Slide 163 text

Generate Multiple Tags at Once 33 From José Valim

Articles

<% @articles.each do |article| %> <%= content_tag_for(:div, article) do %>

<%= article.subject %>

<% end %> <% end %>

Articles

<%= content_tag_for(:div, @articles) do |article| %>

<%= article.subject %>

<% end %>

Slide 164

Slide 164 text

Generate Multiple Tags at Once 33 From José Valim

Articles

<% @articles.each do |article| %> <%= content_tag_for(:div, article) do %>

<%= article.subject %>

<% end %> <% end %>

Articles

<%= content_tag_for(:div, @articles) do |article| %>

<%= article.subject %>

<% end %>

Slide 165

Slide 165 text

Render Any Object 34 From José Valim class Event < ActiveRecord::Base # ... def to_partial_path "events/#{trigger}" # events/edit or events/view end end

Slide 166

Slide 166 text

Render Any Object 34 From José Valim class Event < ActiveRecord::Base # ... def to_partial_path "events/#{trigger}" # events/edit or events/view end end <%= render partial: @events, as: :event %>

Slide 167

Slide 167 text

Render Any Object 34 From José Valim class Event < ActiveRecord::Base # ... def to_partial_path "events/#{trigger}" # events/edit or events/view end end <%= render partial: @events, as: :event %>

Slide 168

Slide 168 text

Render Any Object 34 From José Valim class Event < ActiveRecord::Base # ... def to_partial_path "events/#{trigger}" # events/edit or events/view end end <%= render partial: @events, as: :event %>

Slide 169

Slide 169 text

Group Menu Entries 35 From The Rails View

Slide 170

Slide 170 text

Group Menu Entries 35 From The Rails View <%= select_tag( :grouped_menu, grouped_options_for_select( "Group A" => %w[One Two Three], "Group B" => %w[One Two Three] ) ) %>

Slide 171

Slide 171 text

Group Menu Entries 35 From The Rails View <%= select_tag( :grouped_menu, grouped_options_for_select( "Group A" => %w[One Two Three], "Group B" => %w[One Two Three] ) ) %>

Slide 172

Slide 172 text

Build Forms the Way You Like Them 36 From The Rails View class LabeledFieldsWithErrors < ActionView::Helpers::FormBuilder def errors_for(attribute) if (errors = object.errors[attribute]).any? @template.content_tag(:span, errors.to_sentence, class: "error") end end def method_missing(method, *args, &block) if %r{ \A (?labeled_)? (?\w+?) (?_with_errors)? \z }x =~ method and respond_to?(wrapped) and [labeled, with_errors].any?(&:present?) attribute, tags = args.first, [ ] tags << label(attribute) if labeled.present? tags << send(wrapped, *args, &block) tags << errors_for(attribute) if with_errors.present? tags.join(" ").html_safe else super end end end

Slide 173

Slide 173 text

Build Forms the Way You Like Them 36 From The Rails View class LabeledFieldsWithErrors < ActionView::Helpers::FormBuilder def errors_for(attribute) if (errors = object.errors[attribute]).any? @template.content_tag(:span, errors.to_sentence, class: "error") end end def method_missing(method, *args, &block) if %r{ \A (?labeled_)? (?\w+?) (?_with_errors)? \z }x =~ method and respond_to?(wrapped) and [labeled, with_errors].any?(&:present?) attribute, tags = args.first, [ ] tags << label(attribute) if labeled.present? tags << send(wrapped, *args, &block) tags << errors_for(attribute) if with_errors.present? tags.join(" ").html_safe else super end end end

Slide 174

Slide 174 text

Build Forms the Way You Like Them 36 From The Rails View class LabeledFieldsWithErrors < ActionView::Helpers::FormBuilder def errors_for(attribute) if (errors = object.errors[attribute]).any? @template.content_tag(:span, errors.to_sentence, class: "error") end end def method_missing(method, *args, &block) if %r{ \A (?labeled_)? (?\w+?) (?_with_errors)? \z }x =~ method and respond_to?(wrapped) and [labeled, with_errors].any?(&:present?) attribute, tags = args.first, [ ] tags << label(attribute) if labeled.present? tags << send(wrapped, *args, &block) tags << errors_for(attribute) if with_errors.present? tags.join(" ").html_safe else super end end end

Slide 175

Slide 175 text

Build Forms the Way You Like Them 36 From The Rails View class LabeledFieldsWithErrors < ActionView::Helpers::FormBuilder def errors_for(attribute) if (errors = object.errors[attribute]).any? @template.content_tag(:span, errors.to_sentence, class: "error") end end def method_missing(method, *args, &block) if %r{ \A (?labeled_)? (?\w+?) (?_with_errors)? \z }x =~ method and respond_to?(wrapped) and [labeled, with_errors].any?(&:present?) attribute, tags = args.first, [ ] tags << label(attribute) if labeled.present? tags << send(wrapped, *args, &block) tags << errors_for(attribute) if with_errors.present? tags.join(" ").html_safe else super end end end

Slide 176

Slide 176 text

Build Forms the Way You Like Them 36 From The Rails View # ... module Blog class Application < Rails::Application # ... require "labeled_fields_with_errors" config.action_view.default_form_builder = LabeledFieldsWithErrors config.action_view.field_error_proc = ->(field, _) { field } end end

Slide 177

Slide 177 text

Build Forms the Way You Like Them 36 From The Rails View # ... module Blog class Application < Rails::Application # ... require "labeled_fields_with_errors" config.action_view.default_form_builder = LabeledFieldsWithErrors config.action_view.field_error_proc = ->(field, _) { field } end end

Slide 178

Slide 178 text

Build Forms the Way You Like Them 36 From The Rails View # ... module Blog class Application < Rails::Application # ... require "labeled_fields_with_errors" config.action_view.default_form_builder = LabeledFieldsWithErrors config.action_view.field_error_proc = ->(field, _) { field } end end

Slide 179

Slide 179 text

Build Forms the Way You Like Them 36 From The Rails View <%= form_for @article do |f| %>

<%= f.text_field :subject %>

<%= f.labeled_text_field :subject %>

<%= f.text_field_with_errors :subject %>

<%= f.labeled_text_field_with_errors :subject %>

<%= f.submit %> <% end %>

Slide 180

Slide 180 text

Build Forms the Way You Like Them 36 From The Rails View <%= form_for @article do |f| %>

<%= f.text_field :subject %>

<%= f.labeled_text_field :subject %>

<%= f.text_field_with_errors :subject %>

<%= f.labeled_text_field_with_errors :subject %>

<%= f.submit %> <% end %>

Slide 181

Slide 181 text

Build Forms the Way You Like Them 36 From The Rails View

Subject

can't be blank

Subject can't be blank

Slide 182

Slide 182 text

Build Forms the Way You Like Them 36 From The Rails View

Subject

can't be blank

Subject can't be blank

Slide 183

Slide 183 text

Build Forms the Way You Like Them 36 From The Rails View

Subject

can't be blank

Subject can't be blank

Slide 184

Slide 184 text

Inspire Theme Songs About Your Work http://www.confreaks.com/videos/529-farmhouseconf-ruby-hero-tenderlove 37

Slide 185

Slide 185 text

The Router and Controllers They carry the theme of our applications

Slide 186

Slide 186 text

Route Exceptions From José Valim 38 # ... module Blog class Application < Rails::Application # ... config.exceptions_app = routes end end

Slide 187

Slide 187 text

Route Exceptions From José Valim 38 # ... module Blog class Application < Rails::Application # ... config.exceptions_app = routes end end

Slide 188

Slide 188 text

Route Exceptions From José Valim 38 # ... module Blog class Application < Rails::Application # ... config.exceptions_app = routes end end Blog::Application.routes.draw do # ... match "/404", to: "errors#not_found" end

Slide 189

Slide 189 text

Route Exceptions From José Valim 38 # ... module Blog class Application < Rails::Application # ... config.exceptions_app = routes end end Blog::Application.routes.draw do # ... match "/404", to: "errors#not_found" end

Slide 190

Slide 190 text

Route to Sinatra From Crafting Rails Applications 39 source 'https://rubygems.org' # ... gem "resque", require: "resque/server"

Slide 191

Slide 191 text

Route to Sinatra From Crafting Rails Applications 39 source 'https://rubygems.org' # ... gem "resque", require: "resque/server"

Slide 192

Slide 192 text

Route to Sinatra From Crafting Rails Applications 39 source 'https://rubygems.org' # ... gem "resque", require: "resque/server" module AdminValidator module_function def matches?(request) if (id = request.env["rack.session"]["user_id"]) current_user = User.find_by_id(id) current_user.try(:admin?) else false end end end

Slide 193

Slide 193 text

Route to Sinatra From Crafting Rails Applications 39 source 'https://rubygems.org' # ... gem "resque", require: "resque/server" module AdminValidator module_function def matches?(request) if (id = request.env["rack.session"]["user_id"]) current_user = User.find_by_id(id) current_user.try(:admin?) else false end end end

Slide 194

Slide 194 text

Route to Sinatra From Crafting Rails Applications 39 source 'https://rubygems.org' # ... gem "resque", require: "resque/server" module AdminValidator module_function def matches?(request) if (id = request.env["rack.session"]["user_id"]) current_user = User.find_by_id(id) current_user.try(:admin?) else false end end end

Slide 195

Slide 195 text

Route to Sinatra From Crafting Rails Applications 39 Blog::Application.routes.draw do # ... require "admin_validator" constraints AdminValidator do mount Resque::Server, at: "/admin/resque" end end

Slide 196

Slide 196 text

Route to Sinatra From Crafting Rails Applications 39 Blog::Application.routes.draw do # ... require "admin_validator" constraints AdminValidator do mount Resque::Server, at: "/admin/resque" end end

Slide 197

Slide 197 text

Route to Sinatra From Crafting Rails Applications 39 Blog::Application.routes.draw do # ... require "admin_validator" constraints AdminValidator do mount Resque::Server, at: "/admin/resque" end end

Slide 198

Slide 198 text

Route to Sinatra From Crafting Rails Applications 39 Blog::Application.routes.draw do # ... require "admin_validator" constraints AdminValidator do mount Resque::Server, at: "/admin/resque" end end

Slide 199

Slide 199 text

Stream CSV to Users 40 class ArticlesController < ApplicationController def index respond_to do |format| format.html do @articles = Article.all end format.csv do headers["Content-Disposition"] = %Q{attachment; filename="articles.csv"} self.response_body = Enumerator.new do |response| csv = CSV.new(response, row_sep: "\n") csv << %w[Subject Created Status] Article.find_each do |article| csv << [ article.subject, article.created_at.to_s(:long), article.status ] end end end end end # ... end

Slide 200

Slide 200 text

Stream CSV to Users 40 class ArticlesController < ApplicationController def index respond_to do |format| format.html do @articles = Article.all end format.csv do headers["Content-Disposition"] = %Q{attachment; filename="articles.csv"} self.response_body = Enumerator.new do |response| csv = CSV.new(response, row_sep: "\n") csv << %w[Subject Created Status] Article.find_each do |article| csv << [ article.subject, article.created_at.to_s(:long), article.status ] end end end end end # ... end

Slide 201

Slide 201 text

Stream CSV to Users 40 class ArticlesController < ApplicationController def index respond_to do |format| format.html do @articles = Article.all end format.csv do headers["Content-Disposition"] = %Q{attachment; filename="articles.csv"} self.response_body = Enumerator.new do |response| csv = CSV.new(response, row_sep: "\n") csv << %w[Subject Created Status] Article.find_each do |article| csv << [ article.subject, article.created_at.to_s(:long), article.status ] end end end end end # ... end

Slide 202

Slide 202 text

Stream CSV to Users 40 class ArticlesController < ApplicationController def index respond_to do |format| format.html do @articles = Article.all end format.csv do headers["Content-Disposition"] = %Q{attachment; filename="articles.csv"} self.response_body = Enumerator.new do |response| csv = CSV.new(response, row_sep: "\n") csv << %w[Subject Created Status] Article.find_each do |article| csv << [ article.subject, article.created_at.to_s(:long), article.status ] end end end end end # ... end

Slide 203

Slide 203 text

Stream CSV to Users 40 class ArticlesController < ApplicationController def index respond_to do |format| format.html do @articles = Article.all end format.csv do headers["Content-Disposition"] = %Q{attachment; filename="articles.csv"} self.response_body = Enumerator.new do |response| csv = CSV.new(response, row_sep: "\n") csv << %w[Subject Created Status] Article.find_each do |article| csv << [ article.subject, article.created_at.to_s(:long), article.status ] end end end end end # ... end

Slide 204

Slide 204 text

Stream CSV to Users 40 class ArticlesController < ApplicationController def index respond_to do |format| format.html do @articles = Article.all end format.csv do headers["Content-Disposition"] = %Q{attachment; filename="articles.csv"} self.response_body = Enumerator.new do |response| csv = CSV.new(response, row_sep: "\n") csv << %w[Subject Created Status] Article.find_each do |article| csv << [ article.subject, article.created_at.to_s(:long), article.status ] end end end end end # ... end

Slide 205

Slide 205 text

Do Some Work in the Background From Crafting Rails Applications 41 $ rails g migration add_stats_to_articles stats:text

Slide 206

Slide 206 text

Do Some Work in the Background From Crafting Rails Applications 41 $ rails g migration add_stats_to_articles stats:text

Slide 207

Slide 207 text

Do Some Work in the Background From Crafting Rails Applications 41 class Article < ActiveRecord::Base # ... serialize :stats def calculate_stats words = Hash.new(0) body.to_s.scan(/\S+/) { |word| words[word] += 1 } sleep 10 # simulate a lot of work self.stats = {words: words} end end $ rails g migration add_stats_to_articles stats:text

Slide 208

Slide 208 text

Do Some Work in the Background From Crafting Rails Applications 41 class Article < ActiveRecord::Base # ... serialize :stats def calculate_stats words = Hash.new(0) body.to_s.scan(/\S+/) { |word| words[word] += 1 } sleep 10 # simulate a lot of work self.stats = {words: words} end end $ rails g migration add_stats_to_articles stats:text

Slide 209

Slide 209 text

Do Some Work in the Background From Crafting Rails Applications 41 class Article < ActiveRecord::Base # ... require "thread" def self.queue; @queue ||= Queue.new end def self.thread @thread ||= Thread.new do while job = queue.pop job.call end end end thread # start the Thread end

Slide 210

Slide 210 text

Do Some Work in the Background From Crafting Rails Applications 41 class Article < ActiveRecord::Base # ... require "thread" def self.queue; @queue ||= Queue.new end def self.thread @thread ||= Thread.new do while job = queue.pop job.call end end end thread # start the Thread end

Slide 211

Slide 211 text

Do Some Work in the Background From Crafting Rails Applications 41 class Article < ActiveRecord::Base # ... require "thread" def self.queue; @queue ||= Queue.new end def self.thread @thread ||= Thread.new do while job = queue.pop job.call end end end thread # start the Thread end

Slide 212

Slide 212 text

Do Some Work in the Background From Crafting Rails Applications 41 class Article < ActiveRecord::Base # ... require "thread" def self.queue; @queue ||= Queue.new end def self.thread @thread ||= Thread.new do while job = queue.pop job.call end end end thread # start the Thread end

Slide 213

Slide 213 text

Do Some Work in the Background From Crafting Rails Applications 41 class Article < ActiveRecord::Base # ... require "thread" def self.queue; @queue ||= Queue.new end def self.thread @thread ||= Thread.new do while job = queue.pop job.call end end end thread # start the Thread end

Slide 214

Slide 214 text

Do Some Work in the Background From Crafting Rails Applications 41 class Article < ActiveRecord::Base # ... after_create :add_stats def add_stats self.class.queue << -> { calculate_stats; save } end end

Slide 215

Slide 215 text

Do Some Work in the Background From Crafting Rails Applications 41 class Article < ActiveRecord::Base # ... after_create :add_stats def add_stats self.class.queue << -> { calculate_stats; save } end end

Slide 216

Slide 216 text

Do Some Work in the Background From Crafting Rails Applications 41 $ rails c Loading development environment (Rails 3.2.3) >> Article.create!(subject: "Stats", body: "Lorem ipsum…"); Time.now.strftime("%H:%M:%S") => "15:24:10" >> [Article.last.stats, Time.now.strftime("%H:%M:%S")] => [nil, "15:24:13"] >> [Article.last.stats, Time.now.strftime("%H:%M:%S")] =>[{:words=>{"Lorem"=>1, "ipsum"=>1, …}, "15:24:26"]

Slide 217

Slide 217 text

Do Some Work in the Background From Crafting Rails Applications 41 $ rails c Loading development environment (Rails 3.2.3) >> Article.create!(subject: "Stats", body: "Lorem ipsum…"); Time.now.strftime("%H:%M:%S") => "15:24:10" >> [Article.last.stats, Time.now.strftime("%H:%M:%S")] => [nil, "15:24:13"] >> [Article.last.stats, Time.now.strftime("%H:%M:%S")] =>[{:words=>{"Lorem"=>1, "ipsum"=>1, …}, "15:24:26"]

Slide 218

Slide 218 text

Do Some Work in the Background From Crafting Rails Applications 41 $ rails c Loading development environment (Rails 3.2.3) >> Article.create!(subject: "Stats", body: "Lorem ipsum…"); Time.now.strftime("%H:%M:%S") => "15:24:10" >> [Article.last.stats, Time.now.strftime("%H:%M:%S")] => [nil, "15:24:13"] >> [Article.last.stats, Time.now.strftime("%H:%M:%S")] =>[{:words=>{"Lorem"=>1, "ipsum"=>1, …}, "15:24:26"]

Slide 219

Slide 219 text

Have We All Learned Something New Yet?!

Slide 220

Slide 220 text

Publish a Static Site Using Rails 42 Static::Application.configure do # ... # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = !!ENV["GENERATING_SITE"] # ... # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = !ENV["GENERATING_SITE"] # Generate digests for assets URLs config.assets.digest = !!ENV["GENERATING_SITE"] # ... end

Slide 221

Slide 221 text

Publish a Static Site Using Rails 42 Static::Application.configure do # ... # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = !!ENV["GENERATING_SITE"] # ... # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = !ENV["GENERATING_SITE"] # Generate digests for assets URLs config.assets.digest = !!ENV["GENERATING_SITE"] # ... end

Slide 222

Slide 222 text

Publish a Static Site Using Rails 42 class ApplicationController < ActionController::Base protect_from_forgery if ENV["GENERATING_SITE"] after_filter do |c| c.cache_page(nil, nil, Zlib::BEST_COMPRESSION) end end end

Slide 223

Slide 223 text

Publish a Static Site Using Rails 42 class ApplicationController < ActionController::Base protect_from_forgery if ENV["GENERATING_SITE"] after_filter do |c| c.cache_page(nil, nil, Zlib::BEST_COMPRESSION) end end end

Slide 224

Slide 224 text

Publish a Static Site Using Rails 42 require "open-uri" namespace :static do desc "Generate a static copy of the site" task :generate => %w[environment assets:precompile] do site = ENV.fetch("RSYNC_SITE_TO") { fail "Must set RSYNC_SITE_TO" } server = spawn( {"GENERATING_SITE" => "true"}, "bundle exec rails s thin -p 3001" ) sleep 10 # FIXME: start when the server is up # ... end

Slide 225

Slide 225 text

Publish a Static Site Using Rails 42 require "open-uri" namespace :static do desc "Generate a static copy of the site" task :generate => %w[environment assets:precompile] do site = ENV.fetch("RSYNC_SITE_TO") { fail "Must set RSYNC_SITE_TO" } server = spawn( {"GENERATING_SITE" => "true"}, "bundle exec rails s thin -p 3001" ) sleep 10 # FIXME: start when the server is up # ... end

Slide 226

Slide 226 text

Publish a Static Site Using Rails 42 require "open-uri" namespace :static do desc "Generate a static copy of the site" task :generate => %w[environment assets:precompile] do # ... # FIXME: improve the following super crude spider paths = %w[/] files = [ ] while path = paths.shift files << File.join("public", path.sub(%r{/\z}, "/index") + ".html") File.unlink(files.last) if File.exist? files.last files << files.last + ".gz" File.unlink(files.last) if File.exist? files.last page = open("http://localhost:3001#{path}") { |url| url.read } page.scan(/]+href="([^"]+)"/) do |link| paths << link.first end end # ... end end

Slide 227

Slide 227 text

Publish a Static Site Using Rails 42 require "open-uri" namespace :static do desc "Generate a static copy of the site" task :generate => %w[environment assets:precompile] do # ... # FIXME: improve the following super crude spider paths = %w[/] files = [ ] while path = paths.shift files << File.join("public", path.sub(%r{/\z}, "/index") + ".html") File.unlink(files.last) if File.exist? files.last files << files.last + ".gz" File.unlink(files.last) if File.exist? files.last page = open("http://localhost:3001#{path}") { |url| url.read } page.scan(/]+href="([^"]+)"/) do |link| paths << link.first end end # ... end end

Slide 228

Slide 228 text

Publish a Static Site Using Rails 42 require "open-uri" namespace :static do desc "Generate a static copy of the site" task :generate => %w[environment assets:precompile] do # ... system("rsync -a public #{site}") Process.kill("INT", server) Process.wait(server) system("bundle exec rake assets:clean") files.each do |file| File.unlink(file) end end end

Slide 229

Slide 229 text

Publish a Static Site Using Rails 42 require "open-uri" namespace :static do desc "Generate a static copy of the site" task :generate => %w[environment assets:precompile] do # ... system("rsync -a public #{site}") Process.kill("INT", server) Process.wait(server) system("bundle exec rake assets:clean") files.each do |file| File.unlink(file) end end end

Slide 230

Slide 230 text

Publish a Static Site Using Rails 42 $ rake static:generate RSYNC_SITE_TO=/Users/james/Desktop

Slide 231

Slide 231 text

Publish a Static Site Using Rails 42 $ rake static:generate RSYNC_SITE_TO=/Users/james/Desktop

Slide 232

Slide 232 text

Did you memorize that?!

Slide 233

Slide 233 text

Did you memorize that?! Slides: http://speakerdeck.com/u/jeg2 Twitter: @JEG2 Email: [email protected]

Slide 234

Slide 234 text

Thanks! Have fun using these Rails tricks