Grab Bag of Ruby and Ruby on Rails Tricks

Episode #158 by Teacher's Avatar David Kimura

Summary

In this episode, we look at various tips and tricks.
development rails model ruby json dev 12:35

Resources

Summary

# Terminal
rails new APP_NAME
rails g scaffold users first_name last_name

# Rails Notes
# TODO some todo message
# FIXME some fixme message
# OPTIMIZE some optimize message

rails notes

# Clear Development Logs
# config/initializers/clear_logs.rb

if Rails.env.development?
  MAX_LOG_SIZE = 10.megabytes
  logs = File.join(Rails.root, 'log', '*.log')
  if Dir[logs].any? { |log| File.size?(log).to_i > MAX_LOG_SIZE }
    $stdout.puts 'Running rails log:clear'
    `rails log:clear`
  end
end

# Sandboxing Rails Console
rails c --sandbox

# Setting Email From Name
# app/mailers/application_mailer.rb

class ApplicationMailer < ActionMailer::Base
  default from: 'Example Application <from@example.com>'
  layout 'mailer'
end

# Using dig and fetch on Hashes
user = {
  user: {
    attributes: {
      first_name: 'john',
      last_name: 'doe'
    },
    address: {
      street: '123 fake street',
      city: 'atlanta',
      state: 'georgia',
      postal_code: '12345',
      location: {
        latitude: 33.748527, 
        longitude: -84.386635
      }
    }
  }
}

user[:user] && user[:user][:address] && user[:user][:address][:street]

user.dig(:user, :address, :street)
user.dig(:user, :address).fetch(:street)
puts user.dig(:user, :address).fetch(:postal_code, 'None Provided')

# Delegating Methods to Another Class
# Terminal

rails g model profile user:references
rails db:migrate

# app/models/profile.rb

class Profile < ApplicationRecord
  belongs_to :user
  # Profile.first.user.first_name
  # Profile.first.first_name
  delegate :first_name, to: :user
end

# Array Setters, Union and Subtraction
2.4.3 :001 > ing1, ing2 = ['salt', 'pepper']

2.4.3 :002 > [1, 2, 3] & [3, 4]
 => [3]

2.4.3 :003 > [1, 2, 3] - [2, 3]
 => [1]

# Ruby Method Source Location and Display
user = User.first
user.fullName
user.method(:fullName).source_location
user.method(:fullName).source
user.method(:fullName).source.display

# Issue Requests from Console
app.get(app.users_path)
app.cookies

# Seeing Installed Gems
gem server