Rails 內時常會用到共用的連結、字串、數字等 config,除了可以寫在 yml 來處理外,也可以安裝現成的 Gem 來使用,這篇將介紹 Configatron,下一篇則是 Config。
  # Gemfile
  gem "configatron"
  bundle exec rails generate configatron:install
  # auto create
  - config/initializers/configatron.rb
  - config/configatron/defaults.rb
  - config/configatron/development.rb
  - config/configatron/production.rb
  - config/configatron/test.rb
這幾個檔案的優先權滿好理解的,一開始 Configatron 會先去讀 default 檔案內的 config,並根據目前的環境會去讀各對應的 config,然後把兩個檔案 merge 起來,如有重複的情況,deault 的設定會被覆蓋掉~
由此可見,如果 config 在各環境下都還是相同的參數時,就直接丟 default 內即可,如果在不同環境下的 config 再放入對應的環境檔案。
  # Put all your default configatron settings here.
  # Example:
  #   configatron.emails.welcome.subject = 'Welcome!'
  #   configatron.emails.sales_reciept.subject = 'Thanks for your order'
  #
  #   configatron.file.storage = :s3
  configatron.sidekiq.admin.password = "tang"
  configatron.sidekiq.admin.username = "chester"
  # rails console
  configatron
  =>
  configatron.sidekiq.admin.password = "tang"
  configatron.sidekiq.admin.username = "chester"
  configatron.to_h
  => {:sidekiq=>{:admin=>{:username=>"chester", :password=>"tang"}}}
也可以透過 configure_from_hash 來寫會比較清楚
  # Put all your default configatron settings here.
  # Example:
  #   configatron.emails.welcome.subject = 'Welcome!'
  #   configatron.emails.sales_reciept.subject = 'Thanks for your order'
  #
  #   configatron.file.storage = :s3
  config = {
    sidekiq: {
      admin: {
        username: "chester",
        password: "tang"
      }
    },
    # ...
  }
  configatron.configure_from_hash(config)
這樣子後不管在哪裡,都可以 configatron 點 key 來拿到底下所有的 values!