开发者

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. 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 containin开发者_运维技巧g 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:

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. 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.

To open the class String in the global namespace, use:

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

because ::String references the class String strictly in the top level / global namespace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜