加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何访问Rack中间件的特定实例?

发布时间:2020-12-17 02:36:55 所属栏目:百科 来源:网络整理
导读:在我的Rails 3.2应用程序中,我必须在某个类类型的中间件实例上调用一个方法. 我试图使用Rails.application.middleware,但这不起作用,因为它只包装中间件类而不是它们的实例. 现在我正在使用Ruby的instance_variable_get和is_a?从Rails.application.app开始
在我的Rails 3.2应用程序中,我必须在某个类类型的中间件实例上调用一个方法.

我试图使用Rails.application.middleware,但这不起作用,因为它只包装中间件类而不是它们的实例.

现在我正在使用Ruby的instance_variable_get和is_a?从Rails.application.app开始走中间件链,但这感觉不对,特别是因为中间件没有指定方式存储上下文.例如,Rack :: Cache :: Context将下一个实例存储在名为@backend的变量中,而大多数其他实例使用@app.

有没有更好的方法来查找中间件实例?

解决方法

您可以将中间件添加到机架环境中,如下例所示:

require 'rack'

class MyMiddleware
  attr_accessor :add_response
  def initialize app
    @app = app
  end
  def call env
    env['my_middleware'] = self # <-- Add self to the rack environment
    response = @app.call(env)
    response.last << @add_response
    response
  end
end

class MyApp
  def call env
    env['my_middleware'].add_response = 'World!' # <-- Access the middleware instance in the app
    [200,{'Content-Type'=>'text/plain'},['Hello']]
  end
end

use MyMiddleware
run MyApp.new

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读