Ruby: module expands from

I am trying to figure out where the module is expanding from Ruby. Right now, the only thing I could come up with was to use callerand select the appropriate line. Is there a more idiomatic and less fragile way to handle this?

module ClassMethods
  def self.extended(base)
    p caller[2]
  end
end
+4
source share
1 answer

I would personally go for something like this (based on OP comment):

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

Assuming you have internal class knowledge base, you can try something like this:

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: I know that this is a giant hack and not very pleasant, I would be interested to know if there are better ways to do something like this.

+2
source

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


All Articles