为我的Rails应用程序创建自定义配置选项的最佳方法?

时间:2009-02-26 21:37:11

标签: ruby-on-rails ruby configuration environment

我需要为我的Rails应用程序创建一个配置选项。对于所有环境都可以是相同的。我发现如果我在environment.rb中设置它,它在我的视图中可用,这正是我想要的......

environment.rb

AUDIOCAST_URI_FORMAT = http://blablalba/blabbitybla/yadda

效果很好。

然而,我有点不安。这是一个很好的方法吗?有没有更时尚的方式?

14 个答案:

答案 0 :(得分:189)

对于不需要存储在数据库表中的常规应用程序配置,我喜欢在 config 目录中创建一个config.yml文件。对于您的示例,它可能如下所示:

defaults: &defaults
  audiocast_uri_format: http://blablalba/blabbitybla/yadda

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

此配置文件从 config / initializers 中的自定义初始化程序加载:

# Rails 2
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]

# Rails 3+
APP_CONFIG = YAML.load_file(Rails.root.join('config/config.yml'))[Rails.env]

如果您使用的是Rails 3,请确保不要在相对配置路径中意外添加前导斜杠。

然后您可以使用以下方法检索值:

uri_format = APP_CONFIG['audiocast_uri_format']

有关详细信息,请参阅this Railscast

答案 1 :(得分:82)

Rails 3版本的初始化代码如下(RAILS_ROOT&amp; RAILS_ENV已弃用)

APP_CONFIG = YAML.load_file(Rails.root.join('config', 'config.yml'))[Rails.env]

此外,Ruby 1.9.3使用Psych使合并密钥区分大小写,因此您需要更改配置文件以将其考虑在内,例如。

defaults: &DEFAULTS
  audiocast_uri_format: http://blablalba/blabbitybla/yadda

development:
  <<: *DEFAULTS

test:
  <<: *DEFAULTS

production:
  <<: *DEFAULTS

答案 2 :(得分:48)

Rails&gt; = 4.2

只需在YAML目录中创建一个config/文件,例如:config/neo4j.yml

neo4j.yml的内容可能如下所示(为简单起见,我在所有环境中使用默认值):

default: &default
  host: localhost
  port: 7474
  username: neo4j
  password: root

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default
config/application.rb中的

module MyApp
  class Application < Rails::Application
    config.neo4j = config_for(:neo4j)
  end
end

现在,您可以访问自定义配置,如下所示:

Rails.configuration.neo4j['host'] #=>localhost
Rails.configuration.neo4j['port'] #=>7474

更多信息

Rails官方API文档将config_for方法描述为:

  

为当前的Rails环境加载config / foo.yml的便利性

如果您不想使用yaml文件

正如Rails官方指南所说:

  

您可以使用config.x属性下的自定义配置通过Rails配置对象配置自己的代码。

示例

config.x.payment_processing.schedule = :daily
config.x.payment_processing.retries  = 3
config.x.super_debugger = true
  

然后可以通过配置对象获得这些配置点:

Rails.configuration.x.payment_processing.schedule # => :daily
Rails.configuration.x.payment_processing.retries  # => 3
Rails.configuration.x.super_debugger              # => true
Rails.configuration.x.super_debugger.not_set      # => nil

Official Reference for config_for method | Official Rails Guide

答案 3 :(得分:24)

第1步:创建config / initializers / appconfig.rb

require 'ostruct'
require 'yaml'

all_config = YAML.load_file("#{Rails.root}/config/config.yml") || {}
env_config = all_config[Rails.env] || {}
AppConfig = OpenStruct.new(env_config)

第2步:创建config / config.yml

common: &common
  facebook:
    key: 'asdjhasxas'
    secret : 'xyz'
  twitter:
    key: 'asdjhasxas'
    secret : 'abx'

development:
  <<: *common

test:
  <<: *common

production:
  <<: *common

第3步:在代码中的任何位置获取常量

facebook_key = AppConfig.facebook['key']
twitter_key  = AppConfig.twitter['key']

答案 4 :(得分:17)

我只是想在Rails 4.2和5中更新这个最新的东西,你现在可以在任何config/**/*.rb文件中执行此操作:

config.x.whatever = 42

(那里有文字x,即config.x.字面上必须是那个,然后你可以在x之后添加你想要的任何东西)

...这将在您的应用中显示为:

Rails.configuration.x.whatever

在此处查看更多内容:http://guides.rubyonrails.org/configuring.html#custom-configuration

答案 5 :(得分:6)

关于此主题的一些额外信息:

APP_CONFIG = YAML.load_file(Rails.root.join('config', 'config.yml'))[Rails.env].with_indifferent_access

“.with_indifferent_access”允许您使用字符串键或等效符号键访问哈希值。

例如。
APP_CONFIG['audiocast_uri_format'] => 'http://blablalba/blabbitybla/yadda' APP_CONFIG[:audiocast_uri_format] => 'http://blablalba/blabbitybla/yadda'

纯粹是一种方便的东西,但我更喜欢将我的钥匙表示为符号。

答案 6 :(得分:5)

我使用类似于John for Rails 3.0 / 3.1的东西,但我首先解析文件:

APP_CONFIG = YAML.load(ERB.new(File.new(File.expand_path('../config.yml', __FILE__)).read).result)[Rails.env]

这允许我在我的配置中使用ERB,如果我需要,比如阅读heroku的redistogo网址:

production:
  <<: *default
  redis:                  <%= ENV['REDISTOGO_URL'] %>

答案 7 :(得分:2)

Rails 4

创建自定义配置yaml并加载它(并使其适用于您的应用)与database_configuration类似。

创建*.yml,在我的情况下,我需要一个redis配置文件。

config/redis.yml

default: &default
  host: localhost
  port: 6379

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default
  host: <%= ENV['ELASTICACHE_HOST'] %>
  port: <%= ENV['ELASTICACHE_PORT'] %>

然后加载配置

config/application.rb

module MyApp
  class Application < Rails::Application

    ## http://guides.rubyonrails.org/configuring.html#initialization-events
    config.before_initialize do
      Rails.configuration.redis_configuration = YAML.load_file("#{Rails.root}/config/redis.yml")
    end

  end
end

访问值:

Rails.configuration.redis_configuration[Rails.env]类似于database.yml

访问Rails.configuration.database_configuration[Rails.env]的方式

答案 8 :(得分:1)

基于Omer Aslam的优雅解决方案,我决定将密钥转换为符号。唯一的变化是:

all_config = YAML.load_file("#{Rails.root}/config/config.yml").with_indifferent_access || {}

这允许您按符号引用值作为键,例如

AppConfig[:twitter][:key]

这似乎更贴近我的眼睛。

(作为答案发布,因为我的声誉不足以评论Omer的回复)

答案 9 :(得分:0)

我喜欢simpleconfig。它允许您进行每个环境配置。

答案 10 :(得分:0)

查看我对Where is the best place to store application parameters : database, file, code...?

的回复

您所拥有的变体,它是对另一个文件的简单引用。它看到environment.rb不是经常更新的,并且没有一堆应用程序特定的东西。 虽然不是你的问题“Rails方式是什么?”的具体答案,也许会有一些关于那个问题的讨论。

答案 11 :(得分:0)

我更喜欢通过全局应用程序堆栈访问设置。我在本地范围内避免了多余的全局变量。

<强>配置/初始化/ myconfig.rb

MyAppName::Application.define_singleton_method("myconfig") {YAML.load_file("#{Rails.root}/config/myconfig.yml") || {}}

并使用。

访问它
MyAppName::Application.myconfig["yamlstuff"]

答案 12 :(得分:0)

我在Rails初始化之前加载设置的方法

允许您在Rails初始化中使用设置并配置每个环境的设置

# config/application.rb
Bundler.require(*Rails.groups)

mode = ENV['RAILS_ENV'] || 'development'
file = File.dirname(__FILE__).concat('/settings.yml')
Settings = YAML.load_file(file).fetch(mode)
Settings.define_singleton_method(:method_missing) {|name| self.fetch(name.to_s, nil)}

您可以通过两种方式获取设置: 设置['email'] Settings.email

答案 13 :(得分:0)

自定义配置的最佳方式,当setup.yml丢失时显示引发消息。

从config / initializers / custom_config.rb

中的自定义初始化程序加载
setting_config = File.join(Rails.root,'config','setting.yml')
raise "#{setting_config} is missing!" unless File.exists? setting_config
config = YAML.load_file(setting_config)[Rails.env].symbolize_keys

@APP_ID = config[:app_id]
@APP_SECRET = config[:app_secret]

在config / setting.yml中创建一个YAML

development:
  app_id: 433387212345678
  app_secret: f43df96fc4f65904083b679412345678

test:
  app_id: 148166412121212
  app_secret: 7409bda8139554d11173a32222121212

production:
  app_id: 148166412121212
  app_secret: 7409bda8139554d11173a32222121212