Sinatra routing options
Sinatra has a great way of defining routing. You define a route, and then define exactly how it responds right in that same spot. Just the right amount of magic! The routes have only a few basic forms, but it’s more than enough to handle most any situation. In my examples I use get, but there’s no reason you can’t use the same routing with post, put, or delete
No option route
get '/about' do haml :about end
Single option
get '/thing/:id' do @thing = Thing.find(params[:id]) haml :thing_show end
Multiple options
get '/thing/:id/subthing/:subid' do @thing = Thing.find(params[:id]) @subthing = SubThing.find(params[:subid]) haml :subthing_show end
Handling file formats
get '/thing.:format' do case params[:format] when 'xml' render_xml when 'json' render_json end end
Handling full subfolders
This one is ugly. There’s apparently a feature request + possible patch out there (as mentioned on the mailing list, but it hasn’t been implemented yet.
get '/archive/*' do star_depth = 1 # /archive comes before the * splat = request.path_info.split('/')[(star_depth + 1)..-1].join('/') splat end
May 19th, 2009 at 10:24 pm
Actually for the subfolders, you can now use a Regexp, or anything that responds to =~ in fact, as long as it doesn’t also respond to to_str
January 7th, 2010 at 9:24 am
as far as handling the full subfolders is there any downside to a this simple approach?
is there a security vulnerability that i am missing?
get ‘/:toplevel/*’ do
splat = params[:splat].join(‘/’)
splat
end
January 7th, 2010 at 10:19 am
From a superficial inspection, your solution looks to do the same thing as mine, with much less mucking around.
Looking at it, there’s probably a security issue if you use it as a reference to a file on the file system, but otherwise it’d be fine. (think of somebody going to /archive/../../../../../../../etc/passwd or whatever).