How do I access session variables from the Draper decorator in Rails?
When I need any object other than a controller to access the request information, I like to use what I think of as a context template. It looks like this:
Write a singleton class that only has the interface your decorator needs (following the principle of interface separability). As an example, let's say that your decorator needs to know if the user is logged in. Make a single LoginContext
with an instance method user_is_logged_in?
. The decorator can find out if the user is logged in by calling LoginContext.instance.user_is_logged_in?
.
Add before_filter
to yours ApplicationController
that sets the singleton attribute user_is_logged_in
to true
or false
according to the session before starting the activity. Optional, if you want to make sure nothing is using LoginContext
outside of the request, make a filter around_filter
and set the attribute nil
after the action user_is_logged_in?
is triggered and write an accessory so that it raises an error if the attribute is null.
The above is for single-threaded Rails application servers, but you can write the same functionality around a separate single-threaded thread if you are using a threaded application server.
source to share