LoginSignup
176
151

More than 3 years have passed since last update.

Ruby on Railsで定数の指定

Last updated at Posted at 2014-01-28

Railsで定数の指定方法は複数あります。

ApplicationControllerに書く

これだとコントローラ同士で有効になります。

ApplicationCotnroller < ActionController::Base
    NUM = 1
    ...
end

別なコントローラでもつかえる。

BookController < ApplicationController  
    def read   
        ## ここに定数いれる
        @number = NUM
    end
end

config/initializers/constants.rbで宣言

module Constants
    ## Constants::NUMでアクセスできる
    NUM = 1
end

## こっちはTITLEでアクセスできる
TITLE = 'Story Of The Ring'

ProductionとDevelopmentで分ける

constants.rbに書いたうえで、

if Rails.env == "production"
    ## 本番の定数
else
    ## 開発の定数
end

SettingsLogic

SettingsLogic

class Settings < Settingslogic
  source "#{Rails.root}/config/application.yml"
  namespace Rails.env
end

initializeの下にこう書いてから、configの下にapplication.ymlとかを用意します。

# config/application.yml
defaults: &defaults
  artist:
    band: Oasis
development:
  <<: *defaults
test:
  <<: *defaults
production:
  <<: *defaults

とかやるとこんな感じでアクセスできます。

Settings.artist.band # > Oasis

20201005
今リポジトリ確認したら最終更新六年前とかで、もう使うのやめた方がいい気がしました。

confg

最近(20201005)はこちら主流かな。定数管理のGemです。これを書いてbundleします。

gem 'config'

RailsのAppの下にconfig/settingsに設定ファイルを置きます。

config/settings/
├── development.yml
├── production.yml
└── test.yml

本番は環境変数でいいなあとか。

admin:
  url:  <%= ENV['ADMIN_DOMAIN'] %>

開発はベタでいい場合の使い分けができます。

admin:
  url:  https://admin.なんたらかんたら.local

もちろん共通のもかけます。その場合は以下のファイルに記述します。

config/settings.yml

読み出しはこうですね。

Settings.admin[:url]

Railsデフォルトでもconfig使える

application.rbに定義。

config.x.preference = config_for(:default_settings).deep_symbolize_keys

こうかく。


## config/default_settings.yml

default: &default
  foo:
    - bar
    - baz

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

Rails標準configの落とし穴

自分は環境固有の設定のためにgemを使ってるんだけど、これをRailsの機能に統合したいっス。でも自分の設定はネストが深すぎて、現在のRails::Application#config_forでは設定のマージができないんスよ

これを

# config/application.yml
shared:
  foo:
    bar:
      baz: 1
development:
  foo:
    bar:
      qux: 2

こうさせてくれんかのう。

# currently
config_for(:application)[:foo][:bar] #=> { qux: 2 }
# I expect
config_for(:application)[:foo][:bar] #=> { baz: 1, qux: 2 }

マージできないから両方できるようにさせてくれえっていうPRなんだけど、同じキーで本番の設定を開発でつかっちゃうとか起こりそうなので気持ち悪いですね。

定数を扱う時は大人しくGemつかっとくのが良さそうです。
(このPRマージされてるんだが事故った話とかそのうちどこかの会社の開発ブログであがりそうですね)

176
151
2

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
176
151