Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 middleware is

  class Auth

    def initialize(app)
      @app = app
    end

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

      @app.call(env)
    end
  end

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 %>
like image 370
user502052 Avatar asked Mar 04 '11 09:03

user502052


1 Answers

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.

like image 103
wanderfalke Avatar answered Oct 07 '22 00:10

wanderfalke