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

后端 未结 4 1444
無奈伤痛
無奈伤痛 2021-01-05 11:08

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.b

4条回答
  •  甜味超标
    2021-01-05 11:21

    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

提交回复
热议问题