How do I access session variables from the Draper decorator in Rails?

I want to be able to access a session variable from Decorator. Now I cannot do this and cannot access the variables of the controller instance, say @session_variable

.

Is there a clean way to achieve this?

Thank!

+3


source to share


1 answer


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.

0


source







All Articles