![](/img/trans.png)
[英]How can I parse a json response.body to store a key's value in ruby on rails?
[英]In rails, can I access response.body in a action before it returns?
在rails中,我可以在操作返回之前访问response.body吗?
假设我想在返回之前做一些最终的字符串替换,是否可以访问response.body,即视图返回的响应?
在控制器中尝试after_filter。
你应该可以从那里编辑你的response.body。 对我来说,我需要删除xml中的一些ASCII字符,因此我这样做了。
after_filter :sanitize_xml
def sanitize_xml
#clean the response body by accessing 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中
穷人的方法是这样做:
str = render_to_string "mycontroller/mytemplate"
str.gsub!(/blah/,'')
render :text => str
您只需在控制器中覆盖rails render函数,如下所示:
def render *args, &block
super
response.body.gsub!(/blah/,'')
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.