Skip to content

Instantly share code, notes, and snippets.

@iamjwc
Created April 26, 2011 14:53
Show Gist options
  • Save iamjwc/942412 to your computer and use it in GitHub Desktop.
Save iamjwc/942412 to your computer and use it in GitHub Desktop.
before_action.rb
module Sinatra::BeforeAction
def before_action(&blk)
before {
# Find all the routes for the given request method
routes = self.class.routes[request.request_method]
# Find the route that matches the pattern/conditions of the
# request and steal the params.
routes.select do |pattern, keys, conditions, block|
process_route(pattern, keys, conditions) { @action_params = params }
@action_params
end
# If there were params stolen, use those to evaluate
# the block passed into .before_action. Must be sure
# to set the params back to what they initially were.
if @action_params
begin
original_params = @params
@params = @action_params
instance_eval(&blk)
ensure
@params = original_params
end
end
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment