includeしたmoduleのconst_missingは実行されないのか
モジュールで定義されていない定数を参照したとき、Module#const_missingが実行されます。
module A AAA = "AAA" def self.const_missing(id) return "BBB" if id == :BBB raise "not found." end end puts A::AAA puts A::BBB
実行結果です。
- AAAは定数として定義されているので普通に参照でき、
- BBBは未定義なのでconst_missingが起動、内部の処理で"BBB"が返されてきます。
AAA BBB
ここまではいいんですが、問題はmodule Aをincludeした場合。
class X include A def hoge puts AAA puts BBB end end X.new.hoge
実行結果です。AAAの方は参照可能ですが、BBBの方はNameErrorになります。どうもこの場合はModule#const_missingは呼び出されないようだ・・・。
AAA C:/xxx/include.rb:17:in `hoge': uninitialized constant X::BBB (NameError) from C:/xxx/include.rb:21
前に作ったプロキシモジュールをincludeすると、はまる可能性が高いのでご注意。