Blake uses "legacy APIs" as a common use case for Sinatra. The reason
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".
Return values must respond to "each"
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.
begin/rescue vs. throw :halt
I hadn't seen a discussion of these two control structures before.
begin/rescue is meant for exceptions and throw
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
When Sinatra, When Rails?
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.
- get bigger apps going quickly
- less pain to get a CRUD app going
- more control
- choose your own conventions
- legacy APIs
- small apps going quickly
- take full advantage of Rack, no special magic to be compatible
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.