简体   繁体   English

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

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

I have a method I want to add to a class in a Rails app. 我有一种方法想要添加到Rails应用程序的类中。 I tried to separate it out into a module, like so: 我试图将其分成一个模块,如下所示:

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"

I know the file containing the module is being loaded correctly because the puts prints correctly when I include the file, but I get an error: 我知道包含模块的文件已正确加载,因为当我包含该文件时, puts可以正确打印,但是出现错误:

undefined method `hurp' for "foobar":String

So how can I do this? 那我该怎么做呢?

module Hah
  class String
    #...
  end
end

is roughly equivalent to: 大致相当于:

class Hah::String
  #...
end

which makes a class Hah::String and does not refer to the class String in the global namespace. 这使得类Hah::String并在全局名称空间中不引用类String Note that the latter only works if module Hah was already declared (with the module keyword, Module.new , etc), while the former declares or re-opens module Hah and then within that scope declares or re-opens class String which, in context, is implicitly class Hah::String . 请注意,后者仅在已经声明了module Hah (使用module关键字Module.new等)的情况下Module.new ,而前者声明或重新打开module Hah ,然后在该范围内声明或重新打开class String ,上下文是隐式class Hah::String

To open the class String in the global namespace, use: 要在全局名称空间中打开String类,请使用:

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

because ::String references the class String strictly in the top level / global namespace. 因为::String严格在顶级/全局命名空间中引用类String

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

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