【问题标题】:Disabled/Custom params_parser per action禁用/自定义 params_parser 每个操作
【发布时间】:2009-10-26 20:59:17
【问题描述】:

我有一个处理 XML 请求的创建操作。我没有使用内置的 params 哈希,而是使用 Nokogiri 根据 XML 模式验证 XML。如果此验证通过,原始 XML 将被存储以供以后处理。

据我所知,XML 被解析了两次:首先 Rails 创建 params 哈希,然后进行 Nokogiri 解析。我一直在寻找禁用参数解析以加快速度的方法,但一无所获。

ActionController::Base.param_parsers[Mime::XML] = lambda do |body|
  # something
end

我知道通常可以使用上述方法自定义 XML 参数解析,但我依赖于其他控制器中的默认行为。

是否可以在每个操作的基础上绕过参数解析?我有什么选择?

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails xml parsing nokogiri params


    【解决方案1】:

    我已经设法使用 Rails Metal 解决了这个问题。相关部分如下所示:

    class ReportMetal
      def self.call(env) 
        if env["PATH_INFO"] =~ /^\/reports/
          request = Rack::Request.new(env)
          if request.post?
            report = Report.new(:raw_xml => request.body.string)
            if report.save # this triggers the nokogiri validation on raw_xml
              return [201, { 'Content-Type' => 'application/xml' }, report.to_xml]
            else
              return [422, { 'Content-Type' => 'application/xml' }, report.errors.to_xml]
            end
          end
        end
        [404, { "Content-Type" => "text/html" }, "Not Found."]
      ensure
        ActiveRecord::Base.clear_active_connections!
      end
    end
    

    谢谢!

    PS:在开发中使用 Apache Bench 进行的简单基准测试显示,标准 Rails 每秒请求数为 22.62,而 Metal 版本每秒请求数为 57.60。

    【讨论】:

    • 这看起来像我需要的 :) 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多