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 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:
undefined method `hurp' for "foobar":String
So how can I do this?
is roughly equivalent to:
which makes a class
Hah::Stringand does not refer to the classStringin the global namespace. Note that the latter only works ifmodule Hahwas already declared (with themodulekeyword,Module.new, etc), while the former declares or re-opensmodule Hahand then within that scope declares or re-opensclass Stringwhich, in context, is implicitlyclass Hah::String.To open the class
Stringin the global namespace, use:because
::Stringreferences the classStringstrictly in the top level / global namespace.