LoginSignup
2
2

More than 5 years have passed since last update.

Railsで定数(APIキーやAPIのURL、消費税掛け率など)を管理するgem「config」の使い方

Posted at

GEM「config」の概要

タイトルにもあるように定数関係を管理するときにconfigは大変便利。
※もともとはrails_configとかっていう名前だったようですね(参考)

インストール

Gemfileに

gem 'config'

で、bundle installしましょう。
その後、

$ rails g config:install
create  config/initializers/config.rb
create  config/settings.yml
create  config/settings.local.yml
create  config/settings
create  config/settings/development.yml
create  config/settings/production.yml
create  config/settings/test.yml
append  .gitignore

コマンドを放つと、色々ファイルがジェネレートされますが、よく使うのは「config/settings.yml」です。
全体的に適用する場合は config/settings.yml に記載を足しましょう。

開発環境(RAILS_ENV=development)だけにとかであれば config/settings/development.yml に記載する。同様にproduction用とかtest用とかのファイルを作ってくれています。

設定例

google:
  api_key: A***S*******R*********AL***8*S****m**p8
price:
  consumption_tax: 1.08

などが書き方。あくまでただのymlなので書きやすい。

api_keyを保存しておいたり、apiの問い合わせ先のURLを書いておいたり、特定条件下のときに必ずつけたいパラメータを書いておいたりとかに使えます。

表示例

= Settings.google.api_key
= Settings.price.consumption_tax

Settingsの後ろに設定した名前を書くだけの簡単仕様です。

2
2
0

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