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

lms picture lms · Oct 9, 2011 · Viewed 23.9k times · Source

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/*'

Answer

Konstantin Haase picture Konstantin Haase · Oct 10, 2011

With negative look-ahead:

before /^(?!\/(join|payment))/ do
  # ...
end

With pass:

 before do
   pass if %w[join payment].include? request.path_info.split('/')[1]
   # ...
 end

Or you could create a custom matcher.