Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 830
Blankman Avatar asked Feb 22 '11 15:02

Blankman


2 Answers

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
like image 86
natnebuer Avatar answered Nov 06 '22 22:11

natnebuer


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)
       [email protected](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

like image 25
Zimbabao Avatar answered Nov 06 '22 22:11

Zimbabao