0

Let's imagine:

module A
   class ClassA
      def MethodA
         puts "I am the original."
      end
   end
end

module B
   module C
      module D

      end
   end
end

Now, say you can only control what happens inside module D (imagine your code is getting required in there), but from here you want to access or even extend module A or class ClassA.

If you attempt:

module A
   class ClassA
      def MethodA
         puts "You have been overridden!"
      end
   end
end

...then later when A::ClassA.MethodA is called, you'll still get "I am the original." This is because all you've really done is defined a new module called A deep inside module D.

How can you write code that will access/extend the true module A at the top level, from deep inside module D?

2
  • 1
    Note: Ruby is a case-sensitive language and capital letters have specific meaning in terms of syntax. Variables and method names should be lower-case letters. Capitals indicate constants of the form ClassName or CONSTANT_NAME.
    – tadman
    Commented Oct 17, 2019 at 16:59
  • When asking a question it helps if you frame it in terms of what you've done, not some hypothetical person ("you") that might do it that way. Please see "How to Ask" and the linked pages and "mcve" Commented Oct 17, 2019 at 20:25

1 Answer 1

1

I worked out the answer to this. You need to prepend A with :: to access the top level explicitly.

module ::A
   class ClassA
      def MethodA
         puts "You have been overridden!"
      end
   end
end

Now, MethodA has truly been overriden and will output "You have been overridden!"

1
  • Note: MethodA is not overridden, it is overwritten. The original is gone. Commented Oct 18, 2019 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.