在rails中,我可以在操作返回之前访问response.body吗?
假设我想在返回之前做一些最终的字符串替换,我可以访问response.body,即视图返回的响应吗?
解决方法
您可以编写机架中间件来进行此类替换.机架代码是.
- 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
将它包含在某个文件中,让我们在RAILS_ROOT / lib文件夹中将其命名为dump_response.rb.
和线
- use Dump::Response
在config.ru中