TheWebs
TheWebs

Reputation: 12923

Get class name from a class nested in a module in ruby

If I give you:

module Something
  module SomethingElse
    class Foo
    end
  end
end

How do you get the class name of "Foo"? In the console, I have something similar to the example, but when I do .name on it it doesn't print out what I expect.

This is whats in my console:

pry(main)> AisisWriter::Controllers::CommentsManagement::CommentsHandler.name
=> "AisisWriter::Controllers::CommentsManagement::CommentsHandler"

What I expect is just "CommentsHandler"

Upvotes: 1

Views: 1483

Answers (3)

Noman Ur Rehman
Noman Ur Rehman

Reputation: 6957

You can do:

AisisWriter::Controllers::CommentsManagement::CommentsHandler.name.split('::').last || ''

Upvotes: 5

La-comadreja
La-comadreja

Reputation: 5755

It's quite simple.

AisisWriter::Controllers::CommentsManagement::CommentsHandler.name.split(':').last

Upvotes: 0

djaszczurowski
djaszczurowski

Reputation: 4515

If you have ActiveSupport included, try demodulize method

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html

Upvotes: 2

Related Questions