RegExp Before Filter in Sinatra
February 19, 2010
Sinatra doesn’t support arguments to the before filtering method for routing. I wrote a very small method to support this.
I suppose the reason why Sinatra’s before filter is so simple is because most of the time a Siantra app only does 1 very small thing. My apps in Sinatra have been getting more complex but I don’t want to incur all the overhead and boiler plate associated with Rails. RegExp-based filtering is good for keeping your code DRY and adding things like authentication only for specific routes, say ones starting with /admin
Here’s what my little extension looks like:
module Sinatra
module RegexpRouteFilter
def before_with_regexp(pattern, &blk)
do
before if request.path =~ pattern
instance_eval(&blk) end
end
end
RegexpRouteFilter
register
end
Here's a sample of how you'd use it in a routes file:
~~~~{.ruby}/^\/admin/) do
before_with_regexp(# call authentication methods here
401, "GO AWAY!"
halt end
'/admin/super_secret' do
get #...
end
'/admin/do_junk' do
get #...
end