Rails 3 /设置自定义环境变量

Mor*_*ger 16 ruby-on-rails-3

我正在尝试创建一个rails应用程序,它在环境是开发环境时为变量分配一个值,在环境是生产环境时为该变量分配另一个值.我想在我的代码中指定两个值(硬连线),并让rails知道根据运行的环境分配给变量的值.我该怎么做呢?

如果它很重要,我稍后访问该变量并在模型的类方法中返回其值.

Jas*_*ble 25

您可以使用初始化程序执行此操作.

# 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
Run Code Online (Sandbox Code Playgroud)

然后在您的应用程序中,调用变量Configuration.json_url

# app/controller/listings_controller.rb
def grab_json
  json_path = "#{Configuration.json_url}/path/to/json"
end
Run Code Online (Sandbox Code Playgroud)

当您在开发模式下运行时,这将访问http://test.domain.com网址.

当您在生产模式下运行时,这将访问http://www.domain.com网址.

  • 使用Rails 3+有一个更好的方法.您可以使用现有的配置来创建config.json_url ='...'我在http://jasonnoble.org/2011/12/updated-rails3-custom-environment-variables.html上进一步解释了它. (8认同)

小智 15

我喜欢在YAML中存储设置.要根据环境进行不同的设置,使用默认值,您可以拥有一个初始化文件(比如说config/initializers/application_config.rb):

APP_CONFIG = YAML.load_file("#{Rails.root}/config/application_config.yml")[Rails.env]
Run Code Online (Sandbox Code Playgroud)

......然后在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
Run Code Online (Sandbox Code Playgroud)

...然后,用中拉出设置 APP_CONFIG[:my_setting]

  • 那你怎么能在代码中使用"APP_CONFIG"呢?我收到一个错误:未初始化的常量MyController :: APP_CONFIG (2认同)