Rails 3/设置自定义环境变量 [英] Rails 3 / Setting Custom Environment Variables

查看:28
本文介绍了Rails 3/设置自定义环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

When you're running in development mode, this will hit the http://test.domain.com URL.

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

When you're running in production mode, this will hit the http://www.domain.com URL.

这篇关于Rails 3/设置自定义环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆