210 - Ruby on Rails - Tips and Tricks

Episode #210 by Teacher's Avatar David Kimura

Summary

Ruby and Ruby on Rails tricks from, dot files, operators, bundling, StimulusJS and more.
rails ruby tricks stimulusjs 13:23

Resources

Summary

# Rails Console
app
helper.number_to_currency(10)
helper.number_to_percentage(42, precision: 2)

User.where(created_at: 10.days.ago..Time.now)

# IRB Console
sort_options = [:id, :title, :author]
# sort = sort_options.include?(params[:sort]) ? params[:sort] : :id
# sort = (sort_options.include?(params[:sort]) && params[:sort]) || :id
sort = params[:sort].presence_in(sort_options) || :id

1 <=> 2 # => -1
10 <=> 2 # => 1
10 <=> 10 # => 0

money = 9.5
"%.2f" % money # => "9.50"

%w{a b} # => ["a", "b"]
%i{a b} # => [:a, :b]

year = 1972
case year
when 1970..1979: "Seventies"
when 1980..1989: "Eighties"
when 1990..1999: "Nineties"
end

# Terminal
rails g model comment user:belongs_to body:text -p

rails log:clear

tail -f log/development.log | grep DEBUG

echo 'gem: --no-document' >> ~/.gemrc

EDITOR=code bundle open <GEMNAME>
EDITOR=code gem open <GEMNAME>

bundle outdated

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

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

# profile.email

# ~/.railsrc
--skip-spring
--no-helper
--no-assets
--no-controller-specs
--no-view-specs

# application_controller.rb
class ApplicationController < ActionController::Base
  def user_signed_in?
    # !current_user.nil?
    !!current_user
  end
end

# Terminal
yarn add stimulus

# app/javascript/packs/application.js
import 'controllers'

# app/javascript/controllers/index.js
import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"

const application = Application.start()
const context = require.context("controllers", true, /\.js$/)
application.load(definitionsFromContext(context))

# app/javascript/controllers/hello/world_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  initialize(){
    console.log("HELLO WORLD")
  }
}

# View
<div data-controller="hello--worlds">