在rails中,我可以在操作返回之前访问response.body吗?

Bla*_*man 6 ruby ruby-on-rails

在rails中,我可以在操作返回之前访问response.body吗?

假设我想在返回之前做一些最终的字符串替换,是否可以访问response.body,即视图返回的响应?

小智 13

Try after_filter in your controller.

You should be able to edit your response.body from there. For me, I needed to remove some ASCII characters in the xml hence I did this.

after_filter :sanitize_xml

def sanitize_xml
   #clean the response body by accessing response.body
Run Code Online (Sandbox Code Playgroud)

  • 我在Rails 4+中使用了这个,使用`before_action`,然后在方法`response.body = response.body.sub(/ Regexp /,'replacement')`中使用它.工作得很好. (2认同)

Zim*_*bao 6

您可以编写机架中间件来进行此类替换.机架代码是.

module Dump
  require 'rack'

  class Response
    def initialize(app)
       @app=app
    end

    def call(env)
       res=@app.call(env)
       res.body #change this and but also update res.length and header["Content-Length"]
       return res
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

将它包含在某个文件中,让我们在RAILS_ROOT/lib文件夹中将其命名为dump_response.rb.和线

use Dump::Response
Run Code Online (Sandbox Code Playgroud)

在config.ru中