What is the issue with the method acces in ancestors chain in Ruby

63 views Asked by At

I have define a method that has few class inside of it and few modules. From one of the classes I am trying to call a method that is defined in a module(inside the common one) and I get an access error. Here is the full hierachy:

module Top
 class NestedClass
   #some code
   NestedModule::method_name
 end

 module NestedModule
   def method_name
     #some code
   end
 end
end

And the error that I get: undefined method 'method_name' for Top::NestedModule:Module

2

There are 2 answers

4
Arup Rakshit On

Write it as :

module Top
  module NestedModule
    def self.method_name
      #some code
    end
  end
  class NestedClass
    #some code
    NestedModule::method_name
  end
end

In your case you did NestedModule::method_name before defining the module NestedModule.

0
Bart On

You cannot call undeclared methods as well as instance module methods directly. Maybe this will clear things out for you:

module Top
  module NestedModule
    def self.module_method
      1
    end

    def instance_method
      2
    end
  end

  class NestedClass
    NestedModule.module_method # => 1
    NestedModule.instance_method(:instance_method) # => #<UnboundMethod: Top::NestedModule#instance_method>

    extend NestedModule
    instance_method # => 2

    include NestedModule
    new.instance_method # => 2
  end
end

And although "NestedModule::module_method" would also work here, the convention is to use dots when calling class/module methods, and double colons when accessing nested modules/classes.