I’m using method_missing to define a class for namespacing constants in a vocabulary. To be effective, I need the vocabulary class to inherit from BasicObject, otherwise none of the standard object methods are available as vocabulary terms (because the method isn’t missing :). However, when I inherit from BasicObject, I find I can’t call utility methods in another module. The following code illustrates the issue in condensed form:
module Foo
class Bar
def self.fubar( s )
"#{s} has been fubar'd"
end
end
end
class V1
def self.method_missing( name )
Foo::Bar.fubar( "#{name} in v1" )
end
end
class V2 < BasicObject
def self.method_missing( name )
Foo::Bar.fubar( "#{name} in v2" )
end
end
# this works
puts V1.xyz
# => xyz in v1 has been fubar'd
# this doesn't
puts V2.xyz
# => NameError: uninitialized constant V2::Foo
What would I need to add to V2 so that it doesn’t produce an unitialized constant error when I try to call the helper module?
It works if you change the method in
V2like this so that name resolution starts in the global scope.I looked it up in the documentation for you: