Sinatra block parameters!

The latest master Sinatra now supports optional block parameters. It captures any parameters in the URL and passes them into the block that defines the action:

get '/hello/:name' do |n|
  "Hello #{n}!"

The params hash is still available as before, so this should not break any existing applications. It will also work with regular expressions. Any captures are yielded in order:

get %r{/hello/([\w]+)/([\w]+)} do |a, b|
  "Hello, #{a} and #{b}!"

Big thanks to rtomayko for accepting my patch, and working with me to get this solid enough to put into Sinatra!

One final note: this feature behaves slightly differently in ruby 1.8 and 1.9. Ruby 1.9 is much stricter about block arity than 1.8 is. If the number of captures in the URL and the arity of the block do not match, 1.9 will raise an exception. 1.8 will likely just ignore the extra parameters and throw up a warning. If you write code that is compatible with 1.9, it will also work with 1.8, as ruby 1.9 is simply more strict.

Brandon Dimcheff
Brandon Dimcheff
Chief Architect

Brandon Dimcheff is a software engineer born and raised in Ann Arbor, Michigan. He uses go for his day job, has fallen in love with Kubernetes, is an aspiring functional programming language nerd, and is an advocate of open source.