Best way to access session from method_missing in model
Frage
I know that model should not be aware of session data but I have a need to access a small bit of state information in the method_missing that is defined on a model. Methods caught by method_missing are invoked by form helpers, i.e.:
client_medias/new.haml:
f.text_field :new_display_name
client_media.rb:
has_many :custom_properties, :as => :extensible
Here 'new_display_name' is a custom property key defined through a polymorphic association. I need to know the context (in my case provided by current_app method accessible in the controller) to get the collection of distinct custom property keys which I am mapping to the dynamic method definitions in method_missing.
Any ideas? I looked into Thread.current and am inclined to use it at this moment.
Lösung
we have a similar problem, where we are handling multiple mandants in a single application. in our case, the context is the mandant, that is identified through the toplevel-domain the user loads the site from.
our approach is to use the logic within I18n to provide a "singleton" that we can access within every part of our application, like it's done with I18n.locale
which uses Thread.current
too.
we then set up the singleton in our application controller as a before filter, so that every other part of the application can use it within the same response.
as a starting point have a look at sven fuchs implementation https://github.com/svenfuchs/i18n/blob/master/lib/i18n.rb