Ruby on Rails – the framework that made Ruby famous
The two web frameworks of the lessons before this one are small on purpose. Ruby on Rails is the big one: David Heinemeier Hansson extracted it from Basecamp in 2004, and GitHub, Shopify and Airbnb grew up on it. Much of what the web takes for granted today – REST-style routes, database migrations, convention over configuration – Rails invented or made popular. Rails is not a library you call: it is a framework that calls your code, as long as you put it where Rails expects it.
A real Rails app has dozens of folders (rails new makes them). But a Rails app also fits in one file – Rails' own bug report templates are written that way – and here Rails 8 runs right in the page. The first cell boots it: Rails comes from the course's gem cache (about 2 MB of Ruby), and starting the application takes a few seconds:
install_gem "rails"
require "rails"
require "action_controller/railtie"
# rails new makes dozens of folders and files - here: a folder for the
# views and the routes file, empty for now
FileUtils.mkdir_p("/tmp/diner/app/views")
FileUtils.mkdir_p("/tmp/diner/config")
File.write("/tmp/diner/config/routes.rb", "Rails.application.routes.draw do
end
")
class DinerApp < Rails::Application
config.root = "/tmp/diner"
config.eager_load = false # load code when it is needed, as in development
config.consider_all_requests_local = true # error pages with details, as in development
config.logger = Logger.new(STDOUT) # the log goes under the page
end
DinerApp.initialize! unless DinerApp.initialized? # a server boots once - so does the app
Rails.versionRails.version answers: a complete Rails is running. With initialize! the application ran its initializers and built its middleware stack, exactly what bin/rails server does before it listens. (The guard unless DinerApp.initialized? lets you run the cell again – an app boots once.)
Rails sorts a web app into three kinds of parts, MVC:
- Routes (
config/routes.rb) say which path belongs to which controller action:get "/menu" => "diner#menu". - A controller (
app/controllers/diner_controller.rb) is a class; each public method is an action that gathers what the page needs. - A view (
app/views/diner/menu.html.erb) is an ERB template (lesson 84) that turns it into HTML – and Rails finds it by its name: the actionmenuofDinerControllerrendersdiner/menu.html.erbwithout being told. That is convention over configuration.
(The M, the model, is the data – Active Record's job, lesson 57.) Here all three live in one cell: the routes file and the views are written into the app's folder, where rails new would have put them, and the controller is a class. reload_routes! does what the development server does by itself when config/routes.rb changes – it reads the file again:
Rails.root.join("config/routes.rb").write(<<~RUBY)
Rails.application.routes.draw do
root "diner#home"
get "/menu" => "diner#menu", as: :menu
get "/hello/:name" => "diner#hello"
end
RUBY
DinerApp.reload_routes!
Rails.root.join("app/views/diner").mkpath
Rails.root.join("app/views/diner/home.html.erb").write(<<~ERB)
<h1>Chunky's Diner</h1>
<p>Welcome! Today's special: bacon.</p>
<%= link_to "See the menu", menu_path %>
ERB
Rails.root.join("app/views/diner/menu.html.erb").write(<<~ERB)
<h2>Menu</h2>
<ul>
<% @dishes.each do |dish| %>
<li><%= dish %></li>
<% end %>
</ul>
<%= link_to "Back", root_path %>
ERB
class DinerController < ActionController::Base
def home
end
def menu
@dishes = ["Bacon", "Egg", "Coffee"]
end
def hello
render plain: "Hello, #{params[:name]}! Nice to see you."
end
end
show_browser DinerApp, "/"Click around in the mini browser – and read the server log under the page: every request is one Started GET "/menu", then Processing by DinerController#menu as HTML, Rendering diner/menu.html.erb and Completed 200 OK in 3ms. That is the Rails log, the first place to look when something goes wrong. Try /pizza in the address bar, a path with no route: Rails' error page even lists every route it knows.
Follow one request: get "/menu" => "diner#menu" sends it to DinerController#menu. The action sets @dishes – and the controller's instance variables are visible in the view; that is how data reaches the template. home is empty: an action needs no code when the view can do it alone. hello renders text instead of a view, with params[:name] from the path. And the links: link_to "Back", root_path – root_path and menu_path are route helpers, written for you from root and as: :menu, so a path is spelled in one place only.
On your computer bin/rails routes prints the route table; here the app lists it itself ((.:format) is optional: /menu.json would reach the same action):
DinerApp.routes.routes.reject(&:internal).each do |route|
target = "#{route.requirements[:controller]}##{route.requirements[:action]}"
puts "#{route.verb.ljust(4)} #{route.path.spec.to_s.ljust(24)} #{target}"
endgem install rails, then rails new diner makes the whole folder tree, bin/rails server serves it at localhost:3000, and bin/rails generate controller diner home menu writes the controller, the two views and the routes for you. This lesson's three parts then live in config/routes.rb, app/controllers/diner_controller.rb and app/views/diner/. Beyond this lesson Rails brings Active Record for the database, forms, sessions, mail, background jobs and Hotwire for the front end – the Getting Started guide builds a small shop in an afternoon.get "/bacon" => "kitchen#bacon" and a KitchenController whose action bacon renders the text CHUNKY BACON!. The mini browser below shows /bacon – for now, Rails' routing error.Rails.root.join("config/routes.rb").write(<<~RUBY)
Rails.application.routes.draw do
root "diner#home"
get "/menu" => "diner#menu", as: :menu
get "/hello/:name" => "diner#hello"
# get "/bacon" => "kitchen#bacon"
end
RUBY
DinerApp.reload_routes!
class KitchenController < ActionController::Base
# def bacon
# render plain: "..."
# end
end
show_browser DinerApp, "/bacon"