DEV Community

Lucian Ghinda
Lucian Ghinda

Posted on • Originally published at allaboutcoding.ghinda.com

How to get class name and module name in Ruby

How to get the class name

To get the class name:

class User
  def call = puts self.class.name
end
User.new.call #=> User
Enter fullscreen mode Exit fullscreen mode

This will work even if the name is namespace inside a module:

module Authenticated
  class Visitor
    def call = puts self.class.name
  end
end
Authenticated::Visitor.new.call #=> Authenticated::Visitor
Enter fullscreen mode Exit fullscreen mode

How to get the module name

Will not work if you call class.name

module Authenticated
  def self.call = puts self.class.name
end
Authenticated.call # will return Module!!
Enter fullscreen mode Exit fullscreen mode

But Module defines an accessor named name

module Visitors
  def self.call = puts self.name
end
Visitors.call # will return Visitors
Enter fullscreen mode Exit fullscreen mode

Yes there is a constant name defined on a Module.

You can of course redefine that if you want:

module Guest
  def self.name = "Another name"
  def self.call = puts self.name
end
Guest.call # will return "Another name"
Enter fullscreen mode Exit fullscreen mode

Bonus: How to get the current method name

Use __method__ for that:

class Admin
  def call(...) = puts __method__
end
Admin.new.call # "call"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)