Index

Ruby on Rails


String

# `strip` on steroids: remove extra whitespaces around and within a string
>  "    The amount   of whitespace    is too    damn high     ".squish


Validations

# Check an AR object's validations: User.first._validators
# Presence
validates :name, presence: true
validates :name, :login, :email, presence: true

# Acceptance (checkbox should be ticked before going further)
validates :terms_of_service, acceptance: true
validates :terms_of_service, acceptance: { accept: 'yes' }

validates :name, length: { minimum: 2 }
validates :bio, length: { maximum: 500 }
validates :password, length: { in: 6..20 }
validates :registration_number, length: { is: 6 }

# Numericality
validates :points, numericality: true
validates :games_played, numericality: { only_integer: true }
  :greater_than
  :greater_than_or_equal_to
  :equal_to
  :less_than
  :less_than_or_equal_to
  :odd
  :even

# Uniqueness
validates :email, uniqueness: true
validates :name, uniqueness: { scope: :year,
  message: "should happen once per year" }
validates :name, uniqueness: { case_sensitive: false }

# "On" (only checks something for the specified operation)
validates :email, uniqueness: true, on: :create # ( only validates uniqueness when Create)
validates :age, numericality: true, on: :update # ( only validates numericality on Update)


Rake commands

List rake tasks
$ rake -T

Inventory of TODO, FIXME, OPTIMIZE, etc... comments in the project
$ rake notes

Boot up the server on 192.168.1.23:3003

  rails s -p 3003 -b 192.168.1.23

"Address already in use - bind(2) for "::1" port 3000"

ps aux | grep "tcp://localhost:3000" | grep -v grep | awk '{print $2}' | xargs kill -9


Queries

User.joins(:customers).where(customer: { age: 40 })
# User.joins(:customers).where("customer.age = 40")


Various

Object.const_set(params["class_name"].classify, Class.new(ActiveRecord::Base)


Console

Execute raw SQL on the db

  conn = ActiveRecord::Base.connection
  conn.execute("SELECT * FROM users")

Require a gem that's installed on the system, but not present in the Gemfile

> gem which awesome_print
 ~> '/usr/local/lib/ruby/gems/1.9.1/gems/awesome_print-1.7.0/lib/awesome_print.rb'
> $: << '/usr/local/lib/ruby/gems/1.9.1/gems/awesome_print-1.7.0/lib'
> require "awesome_print"