改变Rack Middleware中的response.body

rb-*_*rb- 4 rack ruby-on-rails rack-middleware

我正在尝试为Rails 4.2应用程序编写一些Rack Middleware,它使用该gsub方法改变响应体.我找到了使用这样的模式的旧例子:

class MyMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, response = @app.call(env)
    # do some stuff
    [status, headers, response]
  end
end
Run Code Online (Sandbox Code Playgroud)

我发现的是没有setter方法response.body.是否还有其他模式可以开始修改身体?

rb-*_*rb- 8

问题是它需要一个Array作为方法中的第三个参数call.这种模式让我再次工作.

# not real code, just a pattern to follow
class MyMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, response = @app.call(env)
    new_response = make_new_response(response.body)
    # also must reset the Content-Length header if changing body
    headers['Content-Length'] = new_response.length.to_s
    [status, headers, [new_response]]
  end
end
Run Code Online (Sandbox Code Playgroud)