Home > other >  How in Ruby can I get the module in which a module instance method is defined?
How in Ruby can I get the module in which a module instance method is defined?

Time:09-15

Assuming I have:

module X::Y::Z::M
  def foo
  end
end

How in foo can I dynamically determine the module X::Y::Z::M in the foo method? self.class will not work because it will evaluate to the class that includes the module.

CodePudding user response:

You can use Module.nesting method which returns an array of nesting modules, Refer nesting method of Moudle

module X::Y::Z::M
  def foo
    Module.nesting.first
  end
end

CodePudding user response:

I am assuming you mean given an instance of a class that includes the module, how to determine where that method is defined

Suppose you have,

module X::Y::Z::M
  def foo
  end
end

and another class

class Test
  include X::Y::Z::M
end

If you want to know where a method is declared you can do

Test.new.method(:foo).owner #returns X::Y::Z::M

You can also determine this from within foo, in case you cannot hardcode it

module X::Y::Z::M
 def foo
   method(:foo).owner #this will evaluate to X::Y::Z::M
 end
end
  • Related