iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
自我挑戰組

冒險村-30 Day Ruby on Rails Tips Challenge系列 第 17

冒險村17 - Configatron

17 - Configatron

Rails 內時常會用到共用的連結、字串、數字等 config,除了可以寫在 yml 來處理外,也可以安裝現成的 Gem 來使用,這篇將介紹 Configatron,下一篇則是 Config

gem install

  # Gemfile
  gem "configatron"

Installing

  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 再放入對應的環境檔案。

Example

config > configatron > default.rb

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

參考來源

My blog


上一篇
冒險村16 - customize breadcurmb
下一篇
冒險村18 - Config
系列文
冒險村-30 Day Ruby on Rails Tips Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言