Web Development

46.1 Rack: The Foundation

A Rack app = an object responding to call(env) that returns [status, headers, body]. Middleware wraps apps (logging, sessions, auth, CORS). All Ruby web frameworks are built on Rack.

# config.ru
class App
  def call(env)
    req = Rack::Request.new(env)
    case req.path
    when "/" then [200, { "content-type" => "text/plain" }, ["Hello from Rack"]]
    when "/json" then [200, { "content-type" => "application/json" }, [{ ok: true }.to_json]]
    else [404, {}, ["Not Found"]]
    end
  end
end

use Rack::Logger
run App.new
rackup            # or: puma config.ru

46.2 Sinatra

require "sinatra"
require "json"

set :port, 4567
before { content_type :json }

BOOKS = [{ id: 1, title: "Eloquent Ruby" }]

get "/books" do
  BOOKS.to_json
end

get "/books/:id" do
  book = BOOKS.find { it[:id] == params[:id].to_i } or halt 404, { error: "not found" }.to_json
  book.to_json
end

post "/books" do
  data = JSON.parse(request.body.read, symbolize_names: true)
  book = { id: BOOKS.size + 1, title: data.fetch(:title) }
  BOOKS << book
  status 201
  book.to_json
end

get "/hello/:name" do
  content_type :html
  erb :hello, locals: { name: params[:name] }    # views/hello.erb
end

46.3 Other Frameworks and Servers

Ruby on Rails Full-stack MVC (Module 47) Minimal DSL, great for small apps and APIs Routing-tree, fast, plugin-based Modern, modular full-stack framework REST API micro-framework Sinatra-based full stack Threads + workers (the Rails default) Fibers (async), HTTP/2 Unicorn / Pitchfork Iodine, Agoo Fast C-based servers

Templates: ERB, Haml, Slim, Phlex (Ruby components), ViewComponent.