Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Tricks that Rails didn't tell you.

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest. →

Tricks that Rails didn't tell you.

Some Rails tricks to help your productivity.

Kassio Borges

October 18, 2014

Transcript

107 slides
  1. change column null class ChangeNameToNotNullOnAuthors < ActiveRecord::Migration def up change_column

    :authors, :name, :string, null: false end ! def down change_column :authors, :name, :string, null: true end end
  2. change column null class ChangeNameToNotNullOnAuthors < ActiveRecord::Migration def up change_column_null

    :authors, :name, false end ! def down change_column_null :authors, :name, true end end
  3. change column null class ChangeNameToNotNullOnAuthors < ActiveRecord::Migration def change change_column_null

    :authors, :name, false end end ! class ChangeNameToNotNullOnAuthors < ActiveRecord::Migration def change change_column :authors, :name, :string, null: false end end # => ActiveRecord::IrreversibleMigration
  4. change column default class ChangeStatusDefaultOnArticles < ActiveRecord::Migration def up change_column

    :articles, :status, :string, default: 'draft' end ! def down change_column :articles, :status, :string, default: 'published' end end
  5. change column default class ChangeStatusDefaultOnArticles < ActiveRecord::Migration def change change_column_default

    :articles, :status, 'draft' end end # => ActiveRecord::IrreversibleMigration ! class ChangeStatusDefaultOnArticles < ActiveRecord::Migration def change change_column :articles, :status, :string, default: 'draft' end end # => ActiveRecord::IrreversibleMigration
  6. where.not class Article < ActiveRecord::Base scope :not_draft, -> { where

    'status <> draft' } end ! >> Article.not_draft.to_sql SELECT "articles".* FROM "articles" WHERE (status != 'draft')
  7. where.not class Article < ActiveRecord::Base scope :not_draft, -> { where.not

    status: 'draft' } end ! >> Article.not_draft.to_sql SELECT "articles".* FROM "articles" WHERE ("articles"."status" != 'draft')
  8. order: :asc/:desc class Article < ActiveRecord::Base scope :recent, -> {

    order 'created_at DESC' } end ! >> Article.recent SELECT "articles".* FROM "articles" ORDER BY created_at DESC
  9. order: :asc/:desc class Article < ActiveRecord::Base scope :recent, -> {

    order created_at: :desc } end ! >> Article.recent SELECT "articles".* FROM "articles" ORDER BY "articles"."created_at" DESC
  10. benchmark class Article < ActiveRecord::Base def self.expensive_operation sleep 2 'did

    something very expensive' end end ! >> start = Time.now; Article.expensive_operation; Time.now - start => 2.001179
  11. benchmark class Article < ActiveRecord::Base def self.expensive_operation benchmark 'SUPER EXPENSIVE

    OPERATION' do sleep 2 'did something very expensive' end end end ! >> Article.expensive SUPER EXPENSIVE OPERATION (2001.2ms)
  12. validates strict class Comment include ActiveModel::Validations ! attr_accessor :message !

    validates :message, presence: true, strict: true end ! >> Comment.new.valid? # ActiveModel::StrictValidationFailed: Message can't be blank
  13. validates strict class Comment include ActiveModel::Validations ! attr_accessor :message validate

    do |comment| if message.blank? errors.add(:base, 'You need a message!') end end end ! >> Comment.new.valid? # false
  14. validates strict class Comment include ActiveModel::Validations ! attr_accessor :message validate

    do |comment| if message.blank? errors.add(:base, 'You need a message!', strict: true) end end end ! > Comment.new.valid? # ActiveModel::StrictValidationFailed: You need a message!
  15. menu links <li> <%= link_to 'posts', posts_path, class: active?(posts_path) %>

    </li> <li> <%= link_to 'new post', new_post_path, class: active?(new_post_path) %> </li>
  16. menu links <li> <%= link_to 'posts', posts_path, class: active?(posts_path) %>

    </li> <li> <%= link_to 'new post', new_post_path, class: active?(new_post_path) %> </li>
  17. menu links <li> <%= link_to_unless current_path?(posts_path), 'posts', posts_path %> </li>

    <li> <%= link_to_unless current_path?(new_post_path), 'new post', new_post_path %> </li>
  18. I18n + html <%= link_to t('read_more'), article %> ! <a

    href="/articles/281110143-rails-4-2-0-is"> read more </a> en: read_more: 'read more'
  19. I18n + html <%= link_to t('read_more'), article %> ! <a

    href="/articles/281110143-rails-4-2-0-is"> read &lt;b&gt;more&lt;/b&gt; </a> en: read_more: 'read <b>more</b>'
  20. I18n + html en: read_more: 'read <b>more</b>' <%= link_to raw(t('read_more')),

    article %> ! <a href="/articles/281110143-rails-4-2-0-is"> read <b>more</b> </a>
  21. I18n + html en: read_more_html: 'read <b>more</b>' <%= link_to t('read_more_html'),

    article %> ! <a href="/articles/281110143-rails-4-2-0-is"> read <b>more</b> </a>
  22. benchmark <% start = Time.now %> <%= sleep(2); render 'form'

    %> <% Rails.logger.info("EXPENSIVE VIEW #{Time.now - start}") %> ! ! # logger # Rendered posts/_form.html.erb (2.5ms) # EXPENSIVE VIEW 2.003919
  23. benchmark <% benchmark 'EXPENSIVE VIEW' do %> <%= sleep(2); render

    'form' %> <% end %> ! ! # logger # Rendered posts/_form.html.erb (2.3ms) # EXPENSIVE VIEW (2004.5ms)
  24. I18n subject class Notifier < ActionMailer::Base default from: "[email protected]" !

    # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.notifier.new_article.subject # def new_article @greeting = "Hi" ! mail to: "[email protected]" end end
  25. I18n subject class Notifier < ActionMailer::Base default from: "[email protected]" !

    # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.notifier.new_article.subject # def new_article @greeting = "Hi" ! mail to: "[email protected]" end end
  26. I18n subject class Notifier < ActionMailer::Base default from: "[email protected]" !

    def new_article @greeting = "Hi" ! mail to: "[email protected]", subject: I18n.t('subjects.new_article') end end en: subjects: new_article: 'New article just published.'
  27. I18n subject class Notifier < ActionMailer::Base default from: "[email protected]" !

    def new_article @greeting = "Hi" ! mail to: "[email protected]" end end en: notifier: new_article: subject: 'New article just published.'
  28. I18n subject en: subjects: new_article: 'New article: %{title}.' def new_article

    @greeting = "Hi" ! mail to: "[email protected]", subject: I18n.t('subjects.new_article', title: 'Clarity is king') end
  29. I18n subject class Notifier < ActionMailer::Base default from: "[email protected]" !

    def new_article @greeting = "Hi" ! mail to: "[email protected]", subject: default_i18n_subject(title: 'Clarity is king') end end en: notifier: new_article: subject: 'New article: %{title}.'
  30. exceptions handling # config/application.rb ! # Use the app's own

    router to display error pages. config.exceptions_app = self.routes
  31. exceptions handling # config/routes.rb ! get "/404", to: "errors#not_found" get

    "/422", to: "errors#unprocessable_entity" get "/500", to: "errors#server_error"
  32. index_by /authors /posts [ { "id": 1, "name": "d4rth_v4der" },

    { "id": 2, "name": "luke_skywalk3r" }, { "id": 3, "name": "han_solo" } ] [ { "text": "@luke, I am your father!", "author": 1 }, { "text": "NOOOOOOOOOOOOO!! (╯°□°)╯︵ ┻━┻", "author": 2 }, { "text": "@luke “ ƅϪƅ“)", "author": 3 } ]
  33. index_by @luke, I am your father!! d4rth_v4der! ---! NOOOOOOOOOOOOOOO!! (╯°□°)╯︵

    ┻━┻! luke_skywalk3r! ---! @luke “ ƅϪƅ“)! han_solo! ---
  34. index_by posts.each do |post| author = authors.select do |a| a.id

    == post.author end.first ! puts post.text puts author.name puts '---' end
  35. index_by posts.each do |post| author = indexed_authors[post.author] ! puts post.text

    puts author.name puts '---' end indexed_author = { 1=>#<Author id=1, name="Kassio Borges">, 2=>#<Author id=2, name="Boring">, }

Other Decks in Programming