加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:45:35 所属栏目:百科 来源:网络整理
导读:class C1 def pr puts 'C1' endendclass C2 C1 def pr puts 'C2' super puts self.method(:pr).source_location endendc = C2.newc.pr 在上面的程序中,可以获得由super(在我们的情况下为C1 :: pr)执行的代码的位置,以及使用source_location方法获取C2 :: pr
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

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

解决方法

从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

当super_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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读