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