I am trying to create a rails application that assigns one value to a variable when the environment is the development environment, and another value to that same variable when the environment is the production environment. I want to specify both values in my code (hardwired), and have rails know which value to assign to the variable based on which environment is running. How do I do this?
In case it is important, I later access that variable and return its value in a class method of a model.
You can do this with initializers.
# config/initializers/configuration.rb
class Configuration
class << self
attr_accessor :json_url
end
end
# config/environments/development.rb
# Put this inside the ______::Application.configure do block
config.after_initialize do
Configuration.json_url = 'http://test.domain.com'
end
# config/environments/production.rb
# Put this inside the ______::Application.configure do block
config.after_initialize do
Configuration.json_url = 'http://www.domain.com'
end
Then in your application, call the variable Configuration.json_url
# app/controller/listings_controller.rb
def grab_json
json_path = "#{Configuration.json_url}/path/to/json"
end
When you're running in development mode, this will hit the http://test.domain.com URL.
When you're running in production mode, this will hit the http://www.domain.com URL.
I like to store settings in YAML. To have different settings based on the environment, with defaults, you can have an initializer file (say config/initializers/application_config.rb
) like this:
APP_CONFIG = YAML.load_file("#{Rails.root}/config/application_config.yml")[Rails.env]
…and then in config/application_config.yml
:
defaults: &defaults
my_setting: "foobar"
development:
# add stuff here to override defaults.
<<: *defaults
test:
<<: *defaults
production:
# add stuff here to override defaults.
<<: *defaults
…then, pull out the settings with APP_CONFIG[:my_setting]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With