Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Module | const_get

概要

Module#const_get(name, inherit = true) -> object

詳細

name で指定される名前の定数の値を返却する。

サンプルコード
require 'tbpgr_utils'

module Hogeable
  HOGEABLE = :hogeable
end

class Hoge
  HOGE = :hoge
end

class ChildHoge < Hoge
  include Hogeable
  CHILD_HOGE = :child_hoge
end

bulk_puts_eval binding, <<-EOS
ChildHoge.const_get :HOGEABLE
ChildHoge.const_get 'HOGEABLE'
ChildHoge.const_get :HOGE
ChildHoge.const_get :CHILD_HOGE
ChildHoge.const_get :CHILD_HOGE, false
EOS
# ChildHoge.const_get :HOGEABLE, false # => inferitをfalseにしたので実行すると継承元の定数を取得できずにErrorになる
# ChildHoge.const_get :HOGE, false # => inferitをfalseにしたので実行すると継承元の定数を取得できずにErrorになる

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

出力

ChildHoge.const_get :HOGEABLE          # => :hogeable
ChildHoge.const_get 'HOGEABLE'         # => :hogeable
ChildHoge.const_get :HOGE              # => :hoge
ChildHoge.const_get :CHILD_HOGE        # => :child_hoge
ChildHoge.const_get :CHILD_HOGE, false # => :child_hoge