LoginSignup
47
48

More than 5 years have passed since last update.

settingslogicで定数を管理する

Last updated at Posted at 2012-08-05

settingslogicはymlで定義した値をモデル経由で読み込む。
DBで管理するほどではないデータの管理に使おうかと。

インストール

Gemfile
gem 'settingslogic'
bundle install

使用方法

app/models/constants.rb
class Constants < Settingslogic
  source "#{Rails.root}/config/constants.yml"
  # こうすることで環境ごとに定数を切り分けられる
  namespace Rails.env
end
config/constants.yml
defaults: &defaults
  hoge_number:
    min: 1
    max: 99

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

読み込み方。

Constants.hoge_number.min

環境を考慮しない場合の使い方

app/models/constants.rb
class Constants < Settingslogic
  source "#{Rails.root}/config/constants.yml"
end
config/constants.yml
hoge_number:
  min: 1
  max: 99

erbを使う

Railsのyaml内でerbが使えるのでこんなこともできる。

config/constants.yml
downloaded_files_root: <%= "#{Rails.root}/tmp/downloaded/" %>

参考

Railsで定数を別ファイルで管理したい? よろしい、ならば Settingslogic だ。 - @sugamasao.blog.title # => ”コードで世界を変えたい”
http://d.hatena.ne.jp/seiunsky/20100912/1284299997

47
48
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
47
48