Is there a way to create a "before" filter to capture and pre-process all POST requests in Sinatra?
4 Answers
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
-
You need Sinatra 1.2.0 or higher for this to work. I just learned it a hard way ;)– BłażejCommented Feb 19, 2014 at 18:42
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
-
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-levelbefore do
namespace.– Arman HCommented 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
+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
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.
-
-
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 HCommented Mar 28, 2013 at 8:58