I have an external ecommerce link that varies based based on environment (testing and production systems).
Where should it go in Rails?
Possibilities include:
- a conditional directly in the template, on the button (not a good solution, IMO)
- database (though there's no model for this so it would be a specific case possibly over-generalized)
- application.rb (which I believe is not recommended for this purpose)
- environment-specific application configs
- initializer
- view helper
- YAML file
- (external) environment variable
- etc.
Where would this typically go in Rails?
Some of these keep the template clean, but put a very specific case far away from the place it's used.
2 Answers 2
Configuration data like this should always be stored in a configuration file. I have the below line in all my rails applications:
# config/application.rb
config.app_config = Rails.application.config_for(:app_config)
You can read more about it here: http://api.rubyonrails.org/classes/Rails/Application.html#method-i-config_for
I store configuration variables like these in YAML files and then load them into the app's configuration in config/application.rb
. I believe this is a standard practice.
Example
I configure a URL for something in a config file. For example, this config file is config/client.yml
:
defaults: &defaults
url: 'localhost:8080'
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults
Then I make it available in my app by adding this line to config/application.rb
:
config.client = config_for(:client)
That line roughly translates to, "Load the configuration specified in config/client.yml
and make it available in the app as Rails.configuration.client
".
Now, I can get the URL anywhere in my app via Rails.configuration.client['url']
.
So three steps:
- Create
.yml
file inconfig/
- Declare the file as a config in
config/application.rb
- Access the config in the app via
Rails.configuration