Building websites – request and response
So far your code simply ran top to bottom. A web server works differently: it waits for requests like GET /menu and sends back responses – usually HTML. Which code answers which path is decided by routes.
Sinatra has been the classic among Ruby's web frameworks since 2007: a route is just a method call with a block. Run the cell – a little browser appears below it:
install_gem "sinatra"
require "sinatra/base"
class Diner < Sinatra::Base
get "/" do
"<h1>Chunky's Diner</h1>
<p>Welcome! Today's special: bacon.</p>
<a href='/menu'>See the menu</a>"
end
get "/menu" do
"<h2>Menu</h2>
<ul><li>Bacon</li><li>Egg</li><li>Coffee</li></ul>
<a href='/'>Back</a>"
end
get "/hello/:name" do
"Hello, #{params[:name]}! Nice to see you."
end
end
show_browser Diner, "/"The mini browser talks directly to your app: click the links, or type a path into the address bar – try /hello/Kaz or even /pizza (a 404!).
How it works: get "/path" do … end registers a route, and the block's return value becomes the response. Parts with a colon like :name are placeholders and end up in params. On a real server you'd start such an app with ruby app.rb and visit localhost:4567 – here the mini browser calls the app directly (both speak Rack, Ruby's web standard).
get "/bacon" returning CHUNKY BACON!. The mini browser below shows /bacon – a 404 for now.install_gem "sinatra"
require "sinatra/base"
class MySite < Sinatra::Base
get "/" do
"<h1>My Site</h1>"
end
# get "/bacon" do
# ...
# end
end
show_browser MySite, "/bacon"