A Sinatra before only filter

In a Sinatra application you can use the ‘before’ filter to run something before every each event.

before do
  puts "I will run all the time..."
end

Here’s a module that will allow you to run code only before certain routes:

module Sinatra

  module BeforeOnlyFilter
    def before_only(routes, &block)
      before do
        routes.map!{|x| x = x.gsub(/\*/, '\w+')}
        routes_regex = routes.map{|x| x = x.gsub(/\//, '\/')}
        instance_eval(&block) if routes_regex.any? {|route| (request.path =~ /^#{route}$/) != nil}
      end
    end
  end

  register BeforeOnlyFilter

end

Use it like below, note that you insert ‘*’ for routes that use variable placeholders like ‘:id’…

before_only(['/post', '/comment/*/user/*']) do
  puts "I will only run before the routes '/post' & '/comment/*/user/*'..."
end

Post a Comment

Your email is never shared. Required fields are marked *

*
*

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word