改变Rack Middleware中的response.body

时间:2015-04-10 15:09:46

标签: ruby-on-rails rack 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

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

1 个答案:

答案 0 :(得分:6)

问题是它需要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