Ruby Cheatsheet

Rails, Web, and Gems

Use this Ruby reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Bundler Recap

bundle init
bundle add faraday
bundle install
bundle exec ruby app.rb
bundle outdated

Use Bundler for repeatable dependency versions. Commit Gemfile.lock for applications; libraries often commit it only when the team wants locked development dependencies.

Gemfile Shape

source "https://rubygems.org"

ruby "3.3.0"

gem "rails", "~> 8.0"
gem "pg"

group :test do
  gem "minitest"
end

Keep runtime, development, and test dependencies separated by groups when the app needs different install sets.

Minimal Rack App

# config.ru
app = proc do |env|
  [200, { "content-type" => "text/plain" }, ["Hello from Rack\n"]]
end

run app

Rack is the low-level Ruby web interface. Rails, Sinatra, and many middleware stacks sit on top of it.

Rails Routes

Rails.application.routes.draw do
  root "home#index"
  resources :users, only: [:index, :show, :create]
  get "/health", to: "health#show"
end

Routes map HTTP verbs and paths to controller actions. Prefer resourceful routes when the shape is CRUD.

Controller Action

class UsersController < ApplicationController
  def show
    user = User.find(params[:id])
    render json: { id: user.id, email: user.email }
  end
end

Controller code should coordinate request parsing, authorization, and response rendering. Put business rules in models, services, or plain Ruby objects.

Active Record Basics

class User < ApplicationRecord
  validates :email, presence: true, uniqueness: true
  has_many :posts
end

User.where(active: true).order(:email).limit(20)
User.find_by(email: "ada@example.com")

Active Record builds parameterized SQL for normal query methods. Be careful with raw SQL fragments and user input.

Rails Console and Tasks

bin/rails console
bin/rails routes
bin/rails db:migrate
bin/rails test
bin/rails runner 'puts User.count'

Use the framework binstubs so commands run with the app's Bundler context.

Web Security Checklist

  • Escape HTML by default; mark strings as HTML-safe only when you know why.
  • Use strong parameters or explicit request schemas.
  • Keep CSRF protection enabled for browser form writes.
  • Store passwords with has_secure_password or a proven auth library.
  • Use parameterized query APIs, not string interpolation in SQL.
  • Keep secrets in credentials, environment variables, or a secret manager.

HTTP Client Example

require "net/http"
require "json"

uri = URI("https://api.example.com/health")
res = Net::HTTP.get_response(uri)
data = JSON.parse(res.body) if res.is_a?(Net::HTTPSuccess)

For production clients, set timeouts and handle retries intentionally. Gems like Faraday provide middleware and cleaner adapters.