All about coding

Ruby and Rails technical content written by Lucian Ghinda

How to get class name and module name in Ruby

#ruby #ruby-on-rails #learning #coding

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"

View posts by tag

#ruby #concurrency #general-advice #life-hack #ruby-on-rails #google-cloud #kubernetes #bash #apis #rest-api #guide #docker #bugs-and-errors #howtos #newbie #programming-languages #programming-tips #til #coding #learning #postgresql #sql #design-patterns #web-api #programming-blogs #programmer #databases #programming #learn-coding #learning-journey #side-project #coding-challenge #design-principles #solid-principles #git #tips #testing #test-driven-development #test-automation #code #shortpost #refactoring #code-review #rails #developer #documentation #focus #blogging #content-creation #share #advice #newsletter #active-record #ai #ai-tools #generative-ai #web-development #errors #cursor-ide #ides #gpt-4 #news #scalability #tailwind-css #chatgpt #opensource #reviews #startups #github #technology #types #sorbet #performance #rubymine #vscode #codesnippet #features #syntax #friendlyrb #conference #directories #writing #summary #animation #articles #podcasts #publishing #patterns #pattern-matching #content #updates #seo-for-developers #marketing #properties #gems #matching #rspec #llm #tools #lsp #claudeai #opencode #mcp #rubocop #quality #planning #products #mvp #upgrade #agentic-ai #skills #superpowers