Help us understand the problem. What is going on with this article?

Ruby on Railsで定数の指定

More than 3 years have passed since last update.

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を使ってます。このGem大好き。Rails5にも対応してます。
https://github.com/binarylogic/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

とかやるとこんな感じでアクセスできます。
Ruby
Settings.artist.band

Oasis

おためしあれん。

srockstyle
都内でエンジニアをやってるすろっくさんです。Webと創作とチョコレートが好きです。AWSやGCPみたいなクラウドインフラ周りやサーバサイドを主に触ってます。好きな言語はRuby。単体で書くのもRails使うのも好きです。 PHP / Golangなんかをたまにごにょってたり。 今は都内の某Web企業でSREしてます。
http://www.srockstyle.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした