Tbpgr Blog

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

Ruby | Module | const_defined?

概要

Module#const_defined?(name, inherit = true) -> bool

詳細

モジュールに name で指定される名前の定数が定義されていれば true を返却します
inherit の値によって継承元も含んで判定するか動作を決めることができる。

サンプルコード
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_defined? :HOGEABLE
ChildHoge.const_defined? :HOGE
ChildHoge.const_defined? :CHILD_HOGE
ChildHoge.const_defined? :HOGEABLE, false
ChildHoge.const_defined? :HOGE, false
ChildHoge.const_defined? :CHILD_HOGE, false
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

出力

ChildHoge.const_defined? :HOGEABLE          # => true
ChildHoge.const_defined? :HOGE              # => true
ChildHoge.const_defined? :CHILD_HOGE        # => true
ChildHoge.const_defined? :HOGEABLE, false   # => false
ChildHoge.const_defined? :HOGE, false       # => false
ChildHoge.const_defined? :CHILD_HOGE, false # => true