Class Source Location

I want to find instance methods defined inside a class (explicitly with def, and not those associated with other type calls attr_accessor)

To do this, I thought about looping the result instance_methods(false)and checking if each method is source_locationthe same as the original location of the class.

How to find class source location?

+4
source share
1 answer

[not really an answer to your problem, but too long for a comment]

source_locationdoesn't seem to help here, as dynamic methods can be created with arbitrary locations:

# my_class.rb

class MyClass
  attr_accessor :foo

  class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
    def bar
    end
  RUBY

  class_eval(<<-RUBY, 'dummy.rb', 42)
    def baz
    end
  RUBY
end

p MyClass.instance_method(:foo).source_location
p MyClass.instance_method(:bar).source_location
p MyClass.instance_method(:baz).source_location

Conclusion:

$ ruby my_class.rb
["my_class.rb", 4]
["my_class.rb", 7]
["dummy.rb", 42]
+4
source

Source: https://habr.com/ru/post/1658337/


All Articles