15

Is there a way to create a "before" filter to capture and pre-process all POST requests in Sinatra?

4 Answers 4

23

One way of doing this would be to create a custom condition to use in the filter:

set(:method) do |method|
  method = method.to_s.upcase
  condition { request.request_method == method }
end

before :method => :post do
  puts "pre-process POST"
end 
1
  • You need Sinatra 1.2.0 or higher for this to work. I just learned it a hard way ;)
    – Błażej
    Commented Feb 19, 2014 at 18:42
14

Your solution is fully valid.

I would do it like this:

before do
  next unless request.post?
  puts "post it is!"
end

Or, you can also use a catch-all post route that then hands on the request (needs to be first post route):

post '*' do
  puts "post it is!"
  pass
end
2
  • Thanks! I didn't even consider the post method. I like the second approach better -- it's more clear what the code is about, and doesn't pollute the higher-level before do namespace.
    – Arman H
    Commented Apr 13, 2013 at 6:46
  • With that second option, I believe you have to make sure that post handler is called before all the other post handlers (that do the "real" post handling work). Commented Sep 10, 2014 at 19:27
12

+1 on matt's answer above... I ended up expanding it to include support for one or many methods like so:

set :method do |*methods|
    methods = methods.map { |m| m.to_s.upcase }
    condition { methods.include?(request.request_method) }
end

before method: [:post, :patch] do
    # something
end
4

I came up with this:

before do
    if request.request_method == "POST"
        puts "pre-process POST"
    end
end

... but if anyone knows a better way, please share.

2
  • Yes that's the way to go, as documented
    – ch4nd4n
    Commented Mar 28, 2013 at 6:31
  • I know about filters. I was wondering if testing the request.request_method is best way to go about creating a global pre-POST filter.
    – Arman H
    Commented Mar 28, 2013 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.