【问题标题】:Before-filter for all POST requests in Sinatra?在 Sinatra 中过滤所有 POST 请求?
【发布时间】:2015-11-11 04:33:22
【问题描述】:

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

【问题讨论】:

    标签: ruby filter sinatra


    【解决方案1】:

    这样做的一种方法是创建一个自定义condition 以在过滤器中使用:

    set(:method) do |method|
      method = method.to_s.upcase
      condition { request.request_method == method }
    end
    
    before :method => :post do
      puts "pre-process POST"
    end 
    

    【讨论】:

    • 您需要 Sinatra 1.2.0 或更高版本才能正常工作。我只是学得很辛苦;)
    【解决方案2】:

    您的解决方案完全有效。

    我会这样做:

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

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

    post '*' do
      puts "post it is!"
      pass
    end
    

    【讨论】:

    • 谢谢!我什至没有考虑过post 方法。我更喜欢第二种方法——它更清楚代码是关于什么的,并且不会污染更高级别的before do 命名空间。
    • 使用第二个选项,我相信您必须确保在 所有其他后处理程序(执行“真正的”后处理工作)之前调用后处理程序。
    【解决方案3】:

    +1 on 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
    

    【讨论】:

      【解决方案4】:

      我想出了这个:

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

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

      【讨论】:

      • 是的,这就是要走的路,就像documented
      • 我知道过滤器。我想知道测试 request.request_method 是否是创建全局 pre-POST 过滤器的最佳方法。
      猜你喜欢
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多