Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 / Setting Custom Environment Variables

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.

like image 464
Morris Singer Avatar asked Jan 25 '11 23:01

Morris Singer


2 Answers

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.

like image 85
Jason Noble Avatar answered Sep 19 '22 05:09

Jason Noble


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]

like image 41
Ned Baldessin Avatar answered Sep 19 '22 05:09

Ned Baldessin