Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self.class.name in a mix-in module

Tags:

ruby

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?

like image 364
akonsu Avatar asked Feb 08 '13 22:02

akonsu


1 Answers

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"
like image 159
Andrew Marshall Avatar answered Sep 28 '22 19:09

Andrew Marshall