在过滤Sinatra中的所有POST请求之前?

Arm*_*n H 15 ruby filter sinatra

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

mat*_*att 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 
Run Code Online (Sandbox Code Playgroud)

  • 那很优雅! (3认同)

Kon*_*ase 12

您的解决方案完全有效.

我会这样做:

before do
  next unless request.post?
  puts "post it is!"
end
Run Code Online (Sandbox Code Playgroud)

或者,您也可以使用全部邮寄路线然后提交请求(需要首先发布路线):

post '*' do
  puts "post it is!"
  pass
end
Run Code Online (Sandbox Code Playgroud)


jme*_*ine 11

关于matt的回答+1 以上...我最终扩展它以包括支持一个或多个方法,如下所示:

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
Run Code Online (Sandbox Code Playgroud)