How do I set a middleware variable that is available throughout my application?

I am using Ruby on Rails 3 and I am trying to use middlewares to set a variable @variable_namethat is available later in controllers.

For example, my middleware

  class Auth

    def initialize(app)
      @app = app
    end

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

      @app.call(env)
    end
  end

The above code sets the variable correctly @accountbut is not available in my application (in controllers, models, views ...). So how can I do this?


I saw this answer , which is a way to do what I need, but I would like to have the variable @account"readily available". That is, without using this method, but making it available, for example, in my views, like this:

<%= debug @account %>
+5
4

'env'. :

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

, "" :

request.env['account']

, , , . - .

+15

, Middelware. :

class ApplicationController < ActionController::Base

  protect_from_forgery

  before_filter :set_my_var

private
  def set_my_var
    @account ||= Account.find(1)
  end

end

, @account

+1

You can have cattr_accessor: my_var in any model and set this variable from middleware to

  MyModel.my_var = 'something'

And you can access this anywhere in the application.

-4
source

Have you tried to create a global Ruby variable?

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

  @app.call(env)
end

and

<%= debug $account %>
-5
source

All Articles