This is the third in a series of short videos. They feature Blake Mizerany discussing Sinatra and Heroku in great technical detail at September’s Boston.rb. Watch Part 1 and Part 2 if you’d like.
Blake uses “legacy APIs” as a common use case for Sinatra. The reason
params[:matches] and super-flexible routing in Sinatra exists is because of work done on an existing non-RESTful, ugly API that sent all the data back in the URL itself (not in JSON or some other format).
This seems to be consistent with the philosophy of “Don’t fear the URLs”.
In order to be Rack-compliant, your return values of Sinatra routes should respond to each. Blake mentions the Ruby 1.9 gotcha that the Rack spec also mentions:
The Body must respond to each and must only yield String values. The Body should not be an instance of String, as this will break in Ruby 1.9. If the Body responds to close, it will be called after iteration. If the Body responds to to_path, it must return a String identifying the location of a file whose contents are identical to that produced by calling each. The Body commonly is an Array of Strings, the application instance itself, or a File-like object.
get '/' do erb(:index) end
The file would be named “index.erb”. Sintra doesn’t use the same “name.format.template” convention because the routes are supposed to be “less magical”. You should know what your response format is based on which route you’re already in.
I hadn’t seen a discussion of these two control structures before.
begin/rescue is meant for exceptions and throw :halt is meant for returning a value and returning to another section of code.
The promise is that this will come in very handy as we dive deeper into Sinatra.
get '/' do halt(404) unless session[:user] # ... end
As Sinatra processes the route, it’s listening for
I cut a section out for space reasons where Blake talks about thanking David Heinemeier Hansson for writing Rails. Blake had been trying to get Ruby into companies for years without much success, then Rails came along and made it acceptable.
At the end of this video, I included a section where Blake shows, in response to an audience question, how to append to an existing body via
I thought his
shotgun command was more interesting, though.
Shotgun is “an automatic reloading version of the rackup command that’s shipped with Rack.” It gets you “application-wide reloading of all source files and templates on each request” by forking into a child process, processing, then exiting the child process.
Note that this is not part of Sinatra at all. This is obviously great for a development environment, but keeps Sinatra clean by being a third party.
throw :haltis so cool in practice.