All about coding

Ruby and Rails technical content written by Lucian Ghinda

How to get class name and module name in Ruby

Markdown version

How to get the class name

To get the class name:

class User
  def call = puts self.class.name
end
User.new.call #=> User

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

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!!

But Module defines an accessor named name

module Visitors
  def self.call = puts self.name
end
Visitors.call # will return Visitors

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"

Bonus: How to get the current method name

Use __method__ for that:

class Admin
  def call(...) = puts __method__
end
Admin.new.call # "call"