jayreed1
jayreed1

Reputation: 172

Ruby -- Get defining class name

How can one get the class a method was defined in?

I've found how to look up descendents and ansestors: Look up all descendants of a class in Ruby

But that doesn't necessarily get me the defining class (last defining class really).

I've found how to get the calling class: Ruby Inheritance Get Caller Class Name

But I want the opposite. I would like how to get the defining class.

I've also tried Module.nesting. That gets me what I want in this case, but I worry it will be inconsistent and not acceptable in a larger codebase of which I don't have ultimate control.

puts RUBY_VERSION


# Test class vs super.
class Super
    def test_func
      puts "#{self.class}, #{ __method__}"
    end
end

class Child < Super
  def test_func2
     self.test_func
  end
end

Child.new.test_func

I had hoped for:

1.8.7

Super, test_func

But got:

1.8.7

Child, test_func

Upvotes: 1

Views: 217

Answers (1)

mechnicov
mechnicov

Reputation: 15372

You asked self.class of Child object and you got it.

You need use Method#owner to return the class or module that defines the method.

class Super
  def test_func
    puts "#{method(__method__).owner}, #{ __method__}"
  end
end

class Child < Super
  def test_func2
     self.test_func
  end
end

Child.new.test_func
# will print: Super, test_func

or just

Child.new.method(:test_func).owner
#=> Super

or

Child.instance_method(:test_func).owner
#=> Super

Upvotes: 6

Related Questions