7

In rails, can I access response.body in a action before it returns?

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?

fl00r
  • 82,987
  • 33
  • 217
  • 237
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

4 Answers4

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
natnebuer
  • 131
  • 1
  • 6
  • 2
    I used this in Rails 4+, using `before_action`, then in the method `response.body = response.body.sub(/Regexp/, 'replacement')`. Worked well. – veritas1 Dec 31 '13 at 13:19
7

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

use Dump::Response

in config.ru

Zimbabao
  • 8,150
  • 3
  • 29
  • 36
2

You can simply overwrite rails render function in a controller, like this:

def render *args, &block
  super
  response.body.gsub!(/blah/,'')
end
Nico
  • 881
  • 1
  • 6
  • 19
1

The poor-man's way is to do this:

str = render_to_string "mycontroller/mytemplate"
str.gsub!(/blah/,'')
render :text => str 
Kevin
  • 4,225
  • 2
  • 37
  • 40