0

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.

egres
  • 294
  • 1
  • 8
  • There are lots of threads on this site that discuss this issue, most will scold you for even considering it. There is one that explains in detail how to make anything available to a model, but be warned, the language is rough and you feel like a real tool for doing it. But it CAN be done, it's just bad practice. search 'session model rails' – RadBrad Apr 26 '12 at 23:13
  • I've done my research both here and on the wider interwebs. I realize it is a bad idea but the only way (that I can think of) to directly passing app_id from controller to method_missing in the model would be to monkeypatch text_field helper which could be a bad idea in its own right. If anyone can come up with a better idea I'd be happy to use it. Or tell me which one is a lesser evil (monkeypatching helper or using Thread.current)? – egres Apr 26 '12 at 23:21

1 Answers1

0

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

phoet
  • 18,688
  • 4
  • 46
  • 74
  • i created a little gem based on our approach to this called whitelabel: https://github.com/phoet/whitelabel – phoet Jun 18 '12 at 10:31