15

有没有办法创建一个“之前”过滤器来捕获和预处理 Sinatra 中的所有 POST 请求?

4

4 回答 4

22

一种方法是创建一个自定义条件以在过滤器中使用:

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

before :method => :post do
  puts "pre-process POST"
end 
于 2013-04-12T18:42:42.260 回答
13

您的解决方案是完全有效的。

我会这样做:

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

或者,您也可以使用包罗万象的发布路线,然后提交请求(需要成为第一个发布路线):

post '*' do
  puts "post it is!"
  pass
end
于 2013-04-12T18:11:51.223 回答
11

+1以上matt的回答...我最终将其扩展为包括对一种或多种方法的支持,如下所示:

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
于 2015-11-10T20:33:22.593 回答
4

我想出了这个:

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

...但如果有人知道更好的方法,请分享。

于 2013-03-27T22:51:06.493 回答