Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby:模块从何处扩展而来_Ruby_Metaprogramming - Fatal编程技术网

Ruby:模块从何处扩展而来

Ruby:模块从何处扩展而来,ruby,metaprogramming,Ruby,Metaprogramming,我试图找出模块在Ruby中的扩展位置。现在我唯一能想到的就是使用caller并选择合适的行。有没有一种更惯用、更不脆弱的处理方式 module ClassMethods def self.extended(base) p caller[2] end end 我个人喜欢这样(根据OP的评论): 假设您对base类有内部知识,您可以尝试以下方法: module ClassMethods def self.extended(base) p base.new.method

我试图找出模块在Ruby中的扩展位置。现在我唯一能想到的就是使用
caller
并选择合适的行。有没有一种更惯用、更不脆弱的处理方式

module ClassMethods
  def self.extended(base)
    p caller[2]
  end
end

我个人喜欢这样(根据OP的评论):


假设您对
base
类有内部知识,您可以尝试以下方法:

module ClassMethods
  def self.extended(base)
    p base.new.method(:superfluous_method).source_location
  end
end

class Foo
  def superfluous_method
  end

  extend ClassMethods
end

PS:我知道这是一个巨大的黑客攻击,不是很好,我很想知道是否有更好的方法来做这样的事情。

你只想找到文件名吗?或者你也想找到具体的行号吗?我只是在找文件的路径。不关心行号。你只是好奇吗,比如出于诊断目的?在实际的代码中使用这种东西可能会有问题。好吧,我在实际的代码中使用它,尽管我不会太依赖它。我正在尝试在项目中自动加载配置文件(如果有)。如果没有,不用担心。这会让人很困惑。让人们直接指定位置可能更好。很好,不过在这一点上,我还可以为模块定义路径:
class Foo;文件\路径=\文件\路径;扩展类方法;结束
。谢谢。如果我的方法最终太痛苦,我可能会用类似的方法来替换它。抱歉,我删除了我之前的回复,它是“是的,非常好的观点,在这种情况下,我更愿意传递文件名,而不是获取常量。”
module ClassMethods
  def self.extended(base)
    p base.new.method(:superfluous_method).source_location
  end
end

class Foo
  def superfluous_method
  end

  extend ClassMethods
end