Alex Rivera | Logout

in Sinatra how do you make a "before" filter that matches all routes except some

Asked 2011-10-09T13:48:10.793
35

I have a Ruby Sinatra app and I have some code which I need to execute on all routes except for a few exceptions. How do I do this?

If I wanted to execute the code on selected routes (whitelist style) I'd do this:

['/join', "/join/*", "/payment/*"].each do |path|
    before path do
        #some code
    end
end

How do I do it the other way round though (blacklist style)? I want to match all routes except '/join', '/join/*' and '/payment/*'

Edit
Report

2 Answers

4

What I did to make a "before all, except..." filter is use a splat, and then run code on splat conditions.

before '/*' do
  unless params[:splat] == 'nofilter' || params[:splat] == 'beta'
    redirect '/beta'
  end
end

This allowed me to make a before filter with a redirect that didn't create a redirect loop

answered 2012-11-12T01:24:01.910
1

You can use Regular Expressions for routing in sinatra

for example:

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

taken from here. there you can find further informations.

to build and test your regex you can use http://rubular.com/

answered 2011-10-09T14:05:19.867

Your Answer