Edited at

~~僕が考えたさいきょうの~~Railsの独自config/*.yml 読み込み処理

More than 1 year has passed since last update.

ガイド読むの大事。

https://guides.rubyonrails.org/v4.2/configuring.html#custom-configuration


config/hoge.yml

default: &default

message: "hoge"

development:
<<: *default

production:
<<: *default
message: "foo"



config/application.rb

module XXXX

class Application < Rails::Application
...
config.x.hoge = ActiveSupport::InheritableOptions.new(config_for(:hoge))
...
end
end

# bin/rails console development

Rails.application.config.x.hoge.message
# => "hoge"

# bin/rails console production
Rails.application.config.x.hoge.message
# => "foo"


以下、車輪の再発明 (はずかしい!)

initializersに定義しといて


config/initializers/load_config.rb

def load_config(key, filepath)

yml = YAML.load_file filepath rescue nil
abort "No such file #{filepath}" unless yml

config = yml[Rails.env]
abort "No such environment #{Rails.env} on #{filepath}" unless config

Rails.application.config.send(
"#{key}=".to_sym,
ActiveSupport::InheritableOptions.new(config.deep_symbolize_keys)
)
end

load_config :hogeconf, Rails.root.join('config', 'hoge.yml')


ファイル置いて


config/hoge.yml

default: &default

message: "hoge"

development:
<<: *default

production:
<<: *default
message: "foo"


実際に使う

# bin/rails console development

Rails.application.config.hogeconf.message
# => "hoge"

# bin/rails console production
Rails.application.config.hogeconf.message
# => "foo"

本当にさいきょうかは知らない