In rails, can I access response.body in a action before it returns?
在rails中,我可以在操作返回之前访问response.body吗?
Say I want to do some final string replacements before it returns, can I get access to response.body i.e. the response that the view returns?
假设我想在返回之前做一些最终的字符串替换,我可以访问response.body,即视图返回的响应吗?
4 个解决方案
#1
6
You can write a rack middleware to do such kind of replacements. Code for the rack is.
您可以编写机架中间件来进行此类替换。机架代码是。
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
include it in some file, lets call it dump_response.rb in RAILS_ROOT/lib folder. And line
将它包含在某个文件中,让我们在RAILS_ROOT / lib文件夹中将其命名为dump_response.rb。和线
use Dump::Response
in config.ru
#2
11
Try after_filter in your controller.
在控制器中尝试after_filter。
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.
你应该可以从那里编辑你的response.body。对我来说,我需要删除xml中的一些ASCII字符,因此我这样做了。
after_filter :sanitize_xml
def sanitize_xml
#clean the response body by accessing response.body
#3
1
The poor-man's way is to do this:
穷人的方法是做到这一点:
str = render_to_string "mycontroller/mytemplate"
str.gsub!(/blah/,'')
render :text => str
#4
1
You can simply overwrite rails render function in a controller, like this:
您可以简单地在控制器中覆盖rails render函数,如下所示:
def render *args, &block
super
response.body.gsub!(/blah/,'')
end
#1
6
You can write a rack middleware to do such kind of replacements. Code for the rack is.
您可以编写机架中间件来进行此类替换。机架代码是。
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
include it in some file, lets call it dump_response.rb in RAILS_ROOT/lib folder. And line
将它包含在某个文件中,让我们在RAILS_ROOT / lib文件夹中将其命名为dump_response.rb。和线
use Dump::Response
in config.ru
#2
11
Try after_filter in your controller.
在控制器中尝试after_filter。
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.
你应该可以从那里编辑你的response.body。对我来说,我需要删除xml中的一些ASCII字符,因此我这样做了。
after_filter :sanitize_xml
def sanitize_xml
#clean the response body by accessing response.body
#3
1
The poor-man's way is to do this:
穷人的方法是做到这一点:
str = render_to_string "mycontroller/mytemplate"
str.gsub!(/blah/,'')
render :text => str
#4
1
You can simply overwrite rails render function in a controller, like this:
您可以简单地在控制器中覆盖rails render函数,如下所示:
def render *args, &block
super
response.body.gsub!(/blah/,'')
end