开发者

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开发者_如何学Go 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]


I use the Yettings gem in Rails 3.2, which allows me to store my application variables in config/yettings.yml like so:

defaults: &defaults
  api_key: asdf12345lkj
  some_number: 999
  an_erb_yetting: <%= "erb stuff works" %>
  some_array:
    - element1
    - element2

development:
  <<: *defaults
  api_key: api key for dev

test:
  <<: *defaults

production:
  <<: *defaults

And access them like this:

#/your_rails_app/config/yetting.yml in production
Yetting.some_number #=> 999
Yetting.api_key #=> "asdf12345lkj"


You can find out the environment like this:

ruby-1.9.2-p0 > Rails.env
  => "development"

Store the value in a global variable in your config/application.rb for example:

$foo = "something"

You could also assign the variable in your config/environments/ files instead of deciding based ond Rails.env in application.rb. Depends on your situation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜