如何找到super执行的代码的source_location?

Ale*_*nov 20 ruby inheritance super

class C1
  def pr
    puts 'C1'
  end
end

class C2 < C1
  def pr
    puts 'C2'
    super
    puts self.method(:pr).source_location
  end
end

c = C2.new
c.pr
Run Code Online (Sandbox Code Playgroud)

在上面的程序中,是否可以获取由super(C1::pr在我们的例子中)执行的代码的位置以及我们C2::pr使用source_location方法获得代码的位置?

buk*_*530 20

从ruby 2.2你可以super_method像这样使用:

Class A
  def pr
    puts "pr"
  end
end

Class B < A
  def pr
    puts "Super method: #{method(:pr).super_method}"
  end
end
Run Code Online (Sandbox Code Playgroud)

super_method返回一个Method时,你可以将它们链接起来找到祖先:

def ancestor(m)
  m = method(m) if m.is_a? Symbol
  super_m = m.super_method
  if super_m.nil?
    return m
  else
    return ancestor super_m
  end
end
Run Code Online (Sandbox Code Playgroud)


Wal*_*man 9

你只需要到达超类,然后用来instance_method从超类中获取方法.

class C2 < C1
  def pr
    puts "C2"
    super
    puts "Child: #{self.method(:pr).source_location}"
    puts "Parent: #{self.class.superclass.instance_method(:pr).source_location}"
  end
end
Run Code Online (Sandbox Code Playgroud)

编辑 -关于检查祖先链的评论,它(令人惊讶地)似乎是不必要的.

class C1
  def pr
    puts "C1"
  end
end

class C2 < C1; end

class C3 < C2
  def pr
    puts "C3"
    super
    puts "Child source location: #{self.method(:pr).source_location}"
    puts "Parent source location: #{self.class.superclass.instance_method(:pr).source_location}"
  end
end

c = C3.new
c.pr
Run Code Online (Sandbox Code Playgroud)

版画

C3
C1
Child source location: ["source_location.rb", 10]
Parent source location: ["source_location.rb", 2]
Run Code Online (Sandbox Code Playgroud)


say*_*now 6

根据@bukk530,super_method可以得到你想要的东西,但通过控制台访问它的一个好方法是

ClassName.new.method(:method_name).super_method.source_location
Run Code Online (Sandbox Code Playgroud)


KAR*_*ván 5

如果您使用pry,则可以使用该-s标志来显示 super 方法。有关该功能的文档在此处

show-source Class#method -s
Run Code Online (Sandbox Code Playgroud)