I need information about the user currently logged in available outside
of
controllers. At least in models but probably also in some library code.
I don’t want to pass the user object around everywhere. That is ugly and
annoying. So I wanted to make it available somewhere globally to a
single
request by some before filter that creates the user object from a user
id
stores in session.
Global variables are too global. They are outside the scope of a
request.
I have tried the above with Thread.current[:user] for the user object.
It
seems to work, but is it a good way? I assume a thread may be used for
several requests so if I am not careful the user object may be passed to
some later request? Should I make a after_filter that assigns nil?
Is there a better way to do this?
–
Jesper
16:29:22 up 6:36, 9 users, load average: 0.47, 0.39, 0.32
Jesper Andersen wrote:
I need information about the user currently logged in available outside
of
controllers. At least in models but probably also in some library code.
I don’t want to pass the user object around everywhere. That is ugly and
annoying. So I wanted to make it available somewhere globally to a
single
request by some before filter that creates the user object from a user
id
stores in session.
Sounds like you’re already familiar with filters and the like, so I
won’t bore you with those details, but you can get the same effect as a
global variable by adding a reader and writer to Object. Probably the
easiest way is to add something to your environment.rb:
def outside
@outside
end
def outside=(value)
@outside = value
end
Now you can call self.outside = “blah” and the method outside can be
called from anywhere (at least everywhere I tested :).
Could this code be executed out side of the context of a web request?
Your code will not work well in those situations, for example you are
mandating that unit tests will have to set a “current user”.
In models you typically set the user once, and then forget it and let
the database do all the remembering. Make sure you’re not hanging
yourself.
Eli