I’m creating a model called Configuration and I have the following code and I want to make it more dynamic by using metaprogramming.
In a table on the database for Configuration model I have the following data.
---------------------------------------------------------
variable_name as string | value in text
|
company_name | MyCompany
welcome_text | Welcome to MyCompany's App!
email_order_text | You've just created an account with MyCompany.
year_since | 2012
----------------------------------------------------------
class Configuration < ActiveRecord::Base
#nothing here yet
end
----------------------------------------------------------
Currently, the only way to access the company_name is to do the following in rails console:
configuration_company_name = Configuration.find_by_variable_name("company_name")
configuration_company_name.company_name
> "MyCompany"
I think this is an unacceptable way to do things. First, it will access the database everytime someone checks for the company’s name. I think if I could load it when the app starts and doesn’t have to access it again because it’s in the memory, then it would be better. How can I do something more dynamic so I could access the value “MyCompany” like this.
Configuration.company_name
> "MyCompany"
The reason to do this is to give allow fast customization of the application.
Now you can access your configuration as :
If you a large number of configuration parameters, it might be beneficial to pre-load the cache by accessing a configuration parameter in an initializer file. If you have 1000s of configuration variables you might have to consider migrating the cache to
memcachedetc.If you want to access the configuration parameter as a class method:
Now you can access the parameter as follows: