10 Tips and Tricks

Episode #299 by David Kimura

Summary

I don't get around to doing these too often, but they are always a lot of fun. In this episode, we'll look at ten different Ruby on Rails tips and tricks.
rails tips tricks 10:51

Resources

This episode is sponsored by Honeybadger

Summary

1. Rails Notes


# Code Comments
    # TODO: domain_name_in_email needs to be implemented
    # OPTIMIZE: name_in_email is very slow and needs to be reworked
    # FIXME: email_upcase raises an exception

# Terminal
bin/rails notes

app/models/user.rb:
  * [ 5] [TODO] domain_name_in_email needs to be implemented
  * [ 9] [OPTIMIZE] name_in_email is very slow and needs to be reworked
  * [15] [FIXME] email_upcase raises an exception

2. Log Clear


# Terminal
bin/rails log:clear

3. Underscore Method


# irb
1 + 2 + 3
=> 6

sum = _
=> 6

sum
=> 6

4. Console Helpers


# Rails Console
helper.number_to_currency(42.50)
=> "$42.50"

helper.pluralize(4, 'taco')
=> "4 tacos"

app.users_path
=> "/users"

app.user_url(User.first)
=> "/users/1"

helper.link_to("Users", app.users_path)
=> "<a href=\"/users\">Users</a>"

5. Class and Instance Methods


# Rails Console
User.instance_methods(false)
=> [:name_in_email, :email_upcase, :domain_name_in_email] 

User.methods(false)
=> [:users_count, :defined_enums, :_validators]

User.methods - ActiveRecord::Base.methods
=> [:users_count]

6. Rails Runner


# Terminal
bin/rails runner "puts User.count"

7. Delegate


# models/profile.rb
class Profile < ApplicationRecord
  belongs_to :user
  # profile.user.email

  # profile.email
  delegate :email, to: :user
end

8. Destroy vs Delete


# Rails Console
User.find(1).destroy
User.destroy_all

User.delete_all

# models/user.rb
has_one :profile, dependent: :destroy
has_one :profile, dependent: :delete

9. Warn on Records Fetched Greater Than


# config/environments/development.rb
Rails.application.configure do
  config.active_record.warn_on_records_fetched_greater_than = 100
  ...
end

10. Loading Config Yaml


# config/app_config.yml
key_one: Key One
key_two: Key Two
key_ruby: <%= Rails.env %>

# config/initializers/app_config.rb
yaml = ActiveSupport::ConfigurationFile.new(
  Rails.root.join('config', 'app_config.yml')
).parse

# Rails.configuration.app_config = yaml

# Rails.configuration.app_config = yaml.with_indifferent_access
# Rails.application.config.app_config['key_one']
# Rails.application.config.app_config[:key_one]


Rails.configuration.app_config = OpenStruct.new(yaml)
# Rails.application.config.app_config.key_one