I’ve defined custom configuration variables in my rails app (APP_CONFIG hash). Ok, now how can I use these variables in my models? Directly calling APP_CONFIG[‘variable’] in models its a not rails way! For example I can use these models without Rails environment. Then APP_CONFIG not be defined.
ATM I use model observer and assign global config variables with instance variables, like this:
def after_initialize model
Mongoid.observers.disable :all do
model.user_id = APP_CONFIG['user_id'])
model.variable = User.find(model.user_id).variable
end
end
But this solution looks like a monkey patch. There is better way?
Or I should keep it simplest and can just define APP_CONFIG hash in new app (not Rails app)?
I’d use dependency injection. If you have an object that needs various config values, you could inject the config object through the constructor:
And if the config is only needed for a single method, simply pass it to the method:
Ruby evaluates parameters when the method is called. The default value allows you to use your config object in development/production without having to manually pass it to the methods and to use a stub instead of the actual config in your tests.
Instead of defining another global variable/constant, you could also use the Rails config instead: