26
24

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-04-02

ガイド読むの大事。
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"

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

26
24
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
24