LoginSignup
0
0

More than 5 years have passed since last update.

includeされたモジュールのメソッドから、includeしたクラスの定数を参照する

Posted at

モジュールの中に定義されたメソッドから、そのモジュールをincludeした側の定数を参照する方法。

この方法だと、NameErrorが起こる。(M::QUUXという定数は存在しないから)

module M
  def quux
    p QUUX # M::QUUXの参照を意味する
  end
end

class C
  QUUX = 'quux'
  include M
end

C.new.quux # => uninitialized constant M::QUUX (NameError) 

includeした側のクラスの定数を参照するには、次のようにすればできる。

module M
  def quux
    p self.class::QUUX # includeしたクラスのQUUXを参照
  end
end

class C
  QUUX = 'quux'
  include M
end

C.new.quux # => "quux"

モジュールをincludeしても、includeされたメソッドの名前空間まで一緒になるわけじゃないみたい。

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