includeããmoduleã®const_missingãå®è¡ãããããã«ããã
æ¨æ¥ã®ç¶ããincludeしたmoduleのconst_missingは実行されないããã§ããããµã¨æãç«ã£ã¦ä»¥ä¸ã®ã³ã¼ãã試ãã¦ã¿ããç¡äºåä½ãã¾ãããæ¦ç¥çã«ã¯ã
- includeããã¯ã©ã¹ã§const_missingãå®ç¾©ãã¦ããã
- ãã®ä¸ã§ãincludeããã¢ã¸ã¥ã¼ã«ããå®ç¾©ãæ¢ãã
ã¨ãããã®ã§ãã
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 class X include A def hoge puts AAA puts BBB end #æªå®ç¾©ã®å®æ°ãåç §ãããå ´åå¼ã³åºããã def self.const_missing(id) #includeãã¦ããã¢ã¸ã¥ã¼ã«ããé ã«æ¢ç´¢ããã included_modules.each {|m| begin return m.const_get(id) rescue NameError end } #ã©ãã«ãå®ç¾©ããã¦ããªããã°ã¨ã©ã¼ raise NameError.new end end X.new.hoge
å®è¡çµæã§ãã
AAA BBB AAA BBB
ãã¦ãããã§ä¸å¿const_missingãå¼ã³åºãããããã«ã¯ãªãã¾ããããincludeå ã¯ã©ã¹ã§ãã¡ãã¡ã¡ã½ãããå®ç¾©ããã®ã¯ãã¾ãã«ãããã©ããã¨ãããã¨ã§ãmoduleã«ä»¥ä¸ã®ã¡ã½ããã追å ã
class Module #ãããã·ã¢ã¸ã¥ã¼ã«ãincludeããã def include_proxy( mod ) include mod class << self def const_missing(id) self.included_modules.each {|m| begin return m.const_get(id) rescue NameError end } raise NameError.new end end end end
ããã§ãæåã®ã³ã¼ãã¯ä»¥ä¸ã®ã¨ããæ¸ããããã«ãªãã¾ãã
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 class X include_proxy A def hoge puts AAA puts BBB end end X.new.hoge
å®è¡çµæã§ãã
AAA BBB AAA BBB