How to set in a middleware a variable accessible in all my application?

前端 未结 4 1908
栀梦
栀梦 2021-02-13 21:39

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.

For example my midd

4条回答
  •  既然无缘
    2021-02-13 22:41

    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.

提交回复
热议问题