8

我正在尝试为 Rails 4.2 应用程序编写一些机架中间件,该应用程序使用该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. 我可以从另一种模式开始修改身体吗?

4

1 回答 1

12

问题是它需要一个数组作为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.bytesize.to_s
    [status, headers, [new_response]]
  end
end
于 2015-04-13T18:46:42.143 回答