LoginSignup
0
0

More than 1 year has passed since last update.

定数の共通化

Last updated at Posted at 2022-04-02

やりたいこと

Rubyで定数の共通化をしたい

どうするか

定数用のモジュールを作って、定数を使いたいクラスなりモジュールでその定数用モジュールをincludeして使う

  1. 定数用のモジュールを作成し、定数を設定
  2. 使いたいクラスなりモジュールでinclude

1. 定数用のモジュールを作成し、定数を設定

HogeConstants.rbを作成し、定数を設定

module HogeConstants
 extend ActiveSupport::Concern

 NEKO = "neko".freeze
 INU = "inu".freeze
 KAERU = "kaeru".freeze
 
end

2.使いたいクラスなりモジュールでinclude

class Hoge < ApplicationRecord
 include HogeConstants

 def neko
   puts HogeConstants::NEKO
 end
end
0
0
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
0
0