I want to be able to access a session variable from the Decorator. Now I can't do so, nor can I access controller instance variables, let's say @session_variable
.
Is there a clean way to achieve this?
Thanks!
I want to be able to access a session variable from the Decorator. Now I can't do so, nor can I access controller instance variables, let's say @session_variable
.
Is there a clean way to achieve this?
Thanks!
When I need any object other than a controller to have access to request information, I like to use what I think of as the Context pattern. It looks like this:
Write a singleton class that has only the interface that your decorator needs (following the Interface Segregation Principle). As an example, let's say that your decorator needs to know whether the user is logged in. Make a LoginContext
singleton with an instance method user_is_logged_in?
. The decorator can find out whether a the user is logged in by calling LoginContext.instance.user_is_logged_in?
.
Add an before_filter
to your ApplicationController
that sets the singleton's user_is_logged_in
attribute to true
or false
according to the session before running the action. Optionally, if you want to make sure that nothing uses the LoginContext
outside of a request, make the filter an around_filter
and set the attribute to nil
after running the action, and write the user_is_logged_in?
accessor so that it raises an error if the attribute is nil.
The above is for single-threaded Rails application servers, but you can write the same functionality around a thread-specific singleton if you use a threaded application server.