繁体   English   中英

我可以从模块内部添加到类定义吗?

[英]Can I add to a class definition from inside a module?

我有一种方法想要添加到Rails应用程序的类中。 我试图将其分成一个模块,如下所示:

module Hah
  class String
    def hurp
      "hurp durp"
    end
  end
end
#make sure the file containing the module is loaded correctly.
puts "Yup, we loaded"

#separate file
include Hah
"foobar".hurp
#should be "hurp durp"

我知道包含模块的文件已正确加载,因为当我包含该文件时, puts可以正确打印,但是出现错误:

undefined method `hurp' for "foobar":String

那我该怎么做呢?

module Hah
  class String
    #...
  end
end

大致相当于:

class Hah::String
  #...
end

这使得类Hah::String并在全局名称空间中不引用类String 请注意,后者仅在已经声明了module Hah (使用module关键字Module.new等)的情况下Module.new ,而前者声明或重新打开module Hah ,然后在该范围内声明或重新打开class String ,上下文是隐式class Hah::String

要在全局名称空间中打开String类,请使用:

module Hah
  class ::String
    #...
  end
end

因为::String严格在顶级/全局命名空间中引用类String

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM