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

2 Comments

  1. Posted October 22, 2010 at 11:19 pm | Permalink

    Thanks a lot. Keep up the good work. This resize method was exactly what I needed.
    God Bless
    The Netmate site for information about all the new technologies

  2. Posted January 10, 2011 at 9:40 am | Permalink

    This is no longer needed, since Sinatra 1.1 supports pattern matching filters.

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