Home > Mobile >  Identifying a Ruby module method invoked by super?
Identifying a Ruby module method invoked by super?

Time:07-16

Ruby 2.7 .

I have methods in a couple of modules that are mixed in, and are invoked with super. Each of the module methods invokes super in turn, so all methods by that name in the mixed-in modules are invoked, although perhaps not in a deterministic order.

My question is: Can a method tell programmatically (as opposed to hard-coding) from what module it's been mixed in?

module A
  def initialize(*args, **kwargs)
    puts("something magic")
  end
end
module B
  def initialize(*args, **kwargs)
    puts("something magic")
  end
end

class C
  include A
  include B

  def initialize(*args, **kwargs)
    puts("actual #{class.name} initialize")
    super
  end
end

When run, this will print three lines. What I'm seeking is something like class.name, specific to each module, that identifies the module that supplied the initialize method that's running. The "something magic* strings would be replaced with this actual magic.

  • Related