带有导轨的Hello World机架中间件3:如何处理所有请求的主体 [英] Hello World rack middleware with rails 3: how to process body of all requests
本文介绍了带有导轨的Hello World机架中间件3:如何处理所有请求的主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想尝试一个简单的机架中间件"hello world",但是我似乎陷入了困境. 似乎主要语法已更改,因为某些示例使用了以下代码:
i want to try out a simple rack middleware "hello world", but i seem to get stuck. it looks like the main sytax changed, since some examples use this code:
require 'rack/utils'
class FooBar
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
body.body << "\nHi from #{self.class}"
[status, headers, body]
end
end
产生错误:
undefined method `<<' for #<ActionDispatch::Response:0x103f07c48>
即使我查看那里的其他代码,我似乎也无法使它们在rails 3.0.3下运行.
even when i look at other codes out there, i cannot seem to get them running with rails 3.0.3.
这是我的具体问题:
- 我如何获得一个简单的机架中间件来运行和修改Rails应用程序的任何输出内容?
- 我应该在哪里放置Rails.application.config.middleware.use声明? (我为此在config/initializers中创建了自己的初始化程序)
非常感谢!
推荐答案
Rails 3.2.12 + :
上一个答案不适用于Rails 3.2.12 +
previous answer does not work for Rails 3.2.12+
这个做:
# in config/application.rb
config.middleware.use 'FooBar'
# in config/initializers/foo_bar.rb
class FooBar
def initialize(app)
@app = app
end
def call(env)
status, headers, response = @app.call(env)
response.body += "\nHi from #{self.class}"
# response.body << "..." WILL NOT WORK
[status, headers, response]
end
end
这篇关于带有导轨的Hello World机架中间件3:如何处理所有请求的主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文