Ruby:扩展模块的地方

时间:2016-11-14 01:44:25

标签: ruby metaprogramming

我试图找出Ruby中扩展模块的位置。现在,我唯一能够提出的就是使用caller并挑出适当的行。是否有更惯用且更不易处理的方式?

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

1 个答案:

答案 0 :(得分:2)

我个人会这样做(基于OP的评论):

module ClassMethods
end

class Object
  def extend_with_path(mod, filename)
    p filename
    self.extend(mod)
  end
end


class Foo
  extend_with_path ClassMethods, __FILE__
end

假设您具有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:我知道这是一个巨大的黑客,并不是很好,我很想知道是否有更好的方法来做这样的事情。

相关问题