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 %>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With