I have a module with methods that write to a log. Into each message I want to put the name of the class that logged this message.
The module can be mixed in using include
or extend
. I need my log to have correct class names in each case.
Distilled code:
module M
def f
self.class.name
end
end
class C
extend M
include M
end
p C.f # => "Class"
p C.new.f # => "C"
As you see, the first call incorrectly prints "Class"
. I want it to be "C"
as well.
How to accomplish this?
No need to resort to hooks, simply change your behavior when self
is a Class
/Module
:
module M
def f
self.is_a?(Module) ? name : self.class.name
end
end
class C
extend M
include M
end
C.f #=> "C"
C.new.f #=> "C"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With