Keith Bennett
Keith Bennett

Reputation: 4970

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

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.

Upvotes: 1

Views: 107

Answers (2)

Ankit
Ankit

Reputation: 6980

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,

# assuming that you have already defined the modules
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(__method__).owner #this will evaluate to X::Y::Z::M
 end
end

Upvotes: 3

Supriya Medankar
Supriya Medankar

Reputation: 211

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

Upvotes: 2

Related Questions