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
end #=> User

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

module Authenticated
  class Visitor
    def call = puts
end #=> Authenticated::Visitor

How to get the module name

Will not work if you call

module Authenticated
  def = puts
end # will return Module!!

But Module defines an accessor named name

module Visitors
  def = puts
end # 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 = "Another name"
  def = puts
end # will return "Another name"

Bonus: How to get the current method name

Use __method__ for that:

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