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.
Thanks!
My first attempt was to call
super_methodto get all the initializers up the stack:Second idea is to use
Module.nesting, I think this is what you're looking for:Actually, never thought about that this could be useful, but it works:
https://rubyapi.org/3.1/o/module#method-c-nesting
https://rubyapi.org/3.1/o/method#method-i-super_method