Ruby-on-rails 为我的 Rails 应用程序创建自定义配置选项的最佳方式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/592554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:00:30  来源:igfitidea点击:

Best way to create custom config options for my Rails app?

ruby-on-railsrubyconfigurationenvironment

提问by Ethan

I need to create one config option for my Rails application. It can be the same for all environments. I found that if I set it in environment.rb, it's available in my views, which is exactly what I want...

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

environment.rb

AUDIOCAST_URI_FORMAT = http://blablalba/blabbitybla/yadda

Works great.

效果很好。

However, I'm a little uneasy. Is this a good way to do it? Is there a way that's more hip?

不过,我有点不安。这是一个很好的方法吗?有没有更时髦的方法?

回答by John Topley

For general application configuration that doesn't need to be stored in a database table, I like to create a config.ymlfile within the configdirectory. For your example, it might look like this:

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

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

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

This configuration file gets loaded from a custom initializer in config/initializers:

此配置文件从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]

If you're using Rails 3, ensure you don't accidentally add a leading slash to your relative config path.

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

You can then retrieve the value using:

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

uri_format = APP_CONFIG['audiocast_uri_format']

See this Railscastfor full details.

有关完整详细信息,请参阅此 Railscast

回答by David Burrows

Rails 3 version of initialiser code is as follows (RAILS_ROOT & RAILS_ENV are deprecated)

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

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

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

Also, Ruby 1.9.3 uses Psych which makes merge keys case sensitive so you'll need to change your config file to take that into account, e.g.

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

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

development:
  <<: *DEFAULTS

test:
  <<: *DEFAULTS

production:
  <<: *DEFAULTS

回答by Ali MasudianPour

Rails >= 4.2

导轨 >= 4.2

Just create a YAMLfile into config/directory, for example: config/neo4j.yml.

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

Content of neo4j.ymlcan be somthing like below(For simplicity, I used default for all environments):

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

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

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

in config/application.rb:

config/application.rb

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

Now, your custom config is accessible like below:

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

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


More info

更多信息

Rails official API document describes config_formethod as:

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

Convenience for loading config/foo.yml for the current Rails env.

方便为当前 Rails 环境加载 config/foo.yml。



If you do not want to use a yamlfile

如果您不想使用yaml文件

As Rails official guide says:

正如 Rails 官方指南所说:

You can configure your own code through the Rails configuration object with custom configuration under the config.xproperty.

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

Example

例子

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

These configuration points are then available through the configuration object:

然后可以通过配置对象使用这些配置点:

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_formethod| Official Rails Guide

config_for方法的官方参考| 官方 Rails 指南

回答by Omer Aslam

Step 1:Create config/initializers/appconfig.rb

第 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)

Step 2:Create config/config.yml

第 2 步:创建 config/config.yml

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

development:
  <<: *common

test:
  <<: *common

production:
  <<: *common

Step 3:Get constants anywhere in the code

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

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

回答by smathy

I just wanted to update this for the latest cool stuff in Rails 4.2 and 5, you can now do this inside any of your config/**/*.rbfiles:

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

config.x.whatever = 42

(and that's a literal xin there, ie. the config.x.literally must be that, and then you can add whatever you want after the x)

(这是一个字面意思x,即config.x.字面意思必须是那个,然后你可以在 之后添加任何你想要的x

...and this will be available in your app as:

...这将在您的应用程序中可用:

Rails.configuration.x.whatever

See more here: http://guides.rubyonrails.org/configuring.html#custom-configuration

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

回答by foomip

Just some extra info on this topic:

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

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

".with_indifferent_access" allows you to access the values in the hash using a string key or with an equivalent symbol key.

“.with_indifferent_access”允许您使用字符串键或等效符号键访问散列中的值。

eg.
APP_CONFIG['audiocast_uri_format'] => 'http://blablalba/blabbitybla/yadda'APP_CONFIG[:audiocast_uri_format] => 'http://blablalba/blabbitybla/yadda'

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

Purely a convenience thing, but I prefer to have my keys represented as symbols.

纯粹是为了方便,但我更喜欢将我的键表示为符号。

回答by Hyman Chu

I use something similar to John for Rails 3.0/3.1, but I have erb parse the file first:

我在 Rails 3.0/3.1 中使用了类似于 John 的东西,但我首先让 erb 解析了文件:

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

This allows me to use ERB in my config if I need to, like reading heroku's redistogo url:

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

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

回答by twmulloy

Rails 4

Rails 4

To create a custom configuration yaml and load it (and make available to your app) similar to how database_configuration.

创建自定义配置 yaml 并加载它(并提供给您的应用程序)类似于database_configuration.

Create your *.yml, in my case I needed a redis configuration file.

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

config/redis.yml

config/redis.yml

default: &default
  host: localhost
  port: 6379

development:
  <<: *default

test:
  <<: *default

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

Then load the configuration

然后加载配置

config/application.rb

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

Access the values:

访问值:

Rails.configuration.redis_configuration[Rails.env]similar to how you can have access to your database.ymlby Rails.configuration.database_configuration[Rails.env]

Rails.configuration.redis_configuration[Rails.env]类似于您可以database.yml通过Rails.configuration.database_configuration[Rails.env]

回答by Kitebuggy

Building on Omer Aslam's elegant solution, I decided to convert the keys into symbols. The only change is:

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

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

This allows you to then reference values by symbols as keys, e.g.

这允许您然后通过符号作为键来引用值,例如

AppConfig[:twitter][:key]

This seems neater to my eyes.

这对我来说似乎更整洁。

(Posted as an answer as my reputation isn't high enough to comment on Omer's reply)

(作为答案发布,因为我的声誉不够高,无法对 Omer 的回复发表评论)

回答by greenif

My way to load Settings before Rails initialize

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

Allows you to use settings in Rails initialization and configure settings per environment

允许您在 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)}

You could get settings in two ways: Settings['email']or Settings.email

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