Self.class.name in a compound module

I have a module with methods that are logged. In each message I want to put the name of the class that registered this message.

The module can be mixed with includeor extend. I need my journal to have the 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 can see, the first call does not print correctly "Class". I want him to be "C".

How to do it?

+5
source share
2 answers

No need to resort to hooks, just change your behavior when selfis 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"
+4
source

You can do it like this, you don’t know if there is a better method.

module M
  def self.included(base)
    base.extend ClassMethods
  end

  def f
    self.class.name
  end

  module ClassMethods
    def f
      self.name
    end
  end
end

class C
  include M
end
+3
source

All Articles