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

发布于 2024-07-13 20:34:00 字数 282 浏览 4 评论 0原文

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

environment.rb

AUDIOCAST_URI_FORMAT = http://blablalba/blabbitybla/yadda

效果很好。

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

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...

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

愁杀 2024-07-20 20:34:00

对于不需要存储在数据库表中的一般应用程序配置,我喜欢在 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']

请参阅此 Railscast 了解完整详细信息。

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

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:

# 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.

You can then retrieve the value using:

uri_format = APP_CONFIG['audiocast_uri_format']

See this Railscast for full details.

ゞ花落谁相伴 2024-07-20 20:34:00

Rails 3 版本的初始化代码如下(RAILS_ROOT 和 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

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

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.

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

development:
  <<: *DEFAULTS

test:
  <<: *DEFAULTS

production:
  <<: *DEFAULTS
再见回来 2024-07-20 20:34:00

Rails >= 4.2

只需在 config/ 目录中创建一个 YAML 文件,例如: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 官方指南所述:

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

示例

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

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

Rails >= 4.2

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

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

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

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

in 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_for method as:

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


If you do not want to use a yaml file

As Rails official guide says:

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

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_for method |
Official Rails Guide

白昼 2024-07-20 20:34:00

第 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']

Step 1: Create 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

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

facebook_key = AppConfig.facebook['key']
twitter_key  = AppConfig.twitter['key']
梦途 2024-07-20 20:34:00

我只是想更新它以获取 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

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/**/*.rb files:

config.x.whatever = 42

(and that's a literal x in there, ie. the config.x. literally must be that, and then you can add whatever you want after the 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

网白 2024-07-20 20:34:00

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

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

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

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

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

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.

eg.
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.

优雅的叶子 2024-07-20 20:34:00

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

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

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

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

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

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:

production:
  <<: *default
  redis:                  <%= ENV['REDISTOGO_URL'] %>
娇纵 2024-07-20 20:34:00

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] 类似如何通过 Rails.configuration.database_configuration[Rails.env] 访问 database.yml

Rails 4

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

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

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

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.yml by Rails.configuration.database_configuration[Rails.env]

§对你不离不弃 2024-07-20 20:34:00

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

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

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

AppConfig[:twitter][:key]

这在我看来更整洁。

(作为答案发布,因为我的声誉不够高,无法评论奥马尔的回复)

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

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)

口干舌燥 2024-07-20 20:34:00

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

I like simpleconfig. It allows you to have per environment configuration.

滴情不沾 2024-07-20 20:34:00

请参阅我对 的回复存储应用程序参数的最佳位置在哪里:数据库、文件、代码...?

您所拥有的内容的一个变体,它是对另一个文件的简单引用。 它发现environment.rb不会不断更新,并且其中没有一堆特定于应用程序的内容。
虽然没有具体回答您的“这是 Rails 方式吗?”的问题,但也许会对此进行一些讨论。

see my response to Where is the best place to store application parameters : database, file, code...?

A variation to what you had in that it's a simple reference to another file. It sees that environment.rb isn't constantly updated and doesn't have a heap of app specific stuff in it.
Though not a specific answer to your question of 'is it the Rails way?', perhaps there'll be some discussion there about that.

狼性发作 2024-07-20 20:34:00

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

config/initializers/myconfig.rb

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

并访问它。

MyAppName::Application.myconfig["yamlstuff"]

I prefer accessing settings through the global application stack. I avoid excess global variables in local scope.

config/initializers/myconfig.rb

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

And access it with.

MyAppName::Application.myconfig["yamlstuff"]
惯饮孤独 2024-07-20 20:34:00

我在 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)}

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

My way to load Settings before Rails initialize

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

# 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

千紇 2024-07-20 20:34:00

我自定义配置的最佳方法是在设置.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

My best way to custom config, with raise message when setting.yml is missing.

gets loaded from a custom initializer in 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]

Create a YAML in config/setting.yml

development:
  app_id: 433387212345678
  app_secret: f43df96fc4f65904083b679412345678

test:
  app_id: 148166412121212
  app_secret: 7409bda8139554d11173a32222121212

production:
  app_id: 148166412121212
  app_secret: 7409bda8139554d11173a32222121212
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文