如何在中间件中设置在我所有应用程序中均可访问的变量? [英] How to set in a middleware a variable accessible in all my application?

查看:92
本文介绍了如何在中间件中设置在我所有应用程序中均可访问的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ruby on Rails 3,并且尝试使用中间件来设置变量@variable_name,以后可以在控制器中访问.

I am using Ruby on Rails 3 and I am trying to use middlewares in order to set a variable @variable_name accessible later in controllers.

例如我的中间件是

  class Auth

    def initialize(app)
      @app = app
    end

    def call(env)
      @account ||= Account.find(1)

      @app.call(env)
    end
  end

上面的代码正确设置了@account变量,但是在我的应用程序中不可用(在控制器,模型,视图等中).所以,我该怎么做?

The above code set properly the @account variable, but that isn't available in my application (in controllers, models, views, ...). So, how can I accomplish that?

我看到了

I seen this answer that is a way to do what I need, but I would like to have the @account variable "directly accessible". That is, without use that way but making that available, for example in my views, like this:

<%= debug @account %>

推荐答案

您可以为此使用'env'.因此,在您的中间件中,您可以执行以下操作:

You can use 'env' for that. So in your middleware you do this:

def call(env)
  env['account'] = Account.find(1)
  @app.call(env)
end

您可以通过在应用程序中使用请求"来获得价值:

You can get the value by using 'request' in your app:

request.env['account']

请不要使用某些人在此处建议的全局变量或类属性.这是使自己陷入困境的肯定方法,而且确实是一种坏习惯.

And please don't use global variables or class attributes as some people suggest here. That's a sure way to get yourself into troubles and really is a bad habit.

这篇关于如何在中间件中设置在我所有应用程序中均可访问的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆