1

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"

1

3 Answers 3

5

You can do:

AisisWriter::Controllers::CommentsManagement::CommentsHandler.name.split('::').last || '' 
Sign up to request clarification or add additional context in comments.

Comments

2

If you have ActiveSupport included, try demodulize method

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

1 Comment

Note that you must call :demodulize on the string, not the class. For instance: A::B::C.name.demodulize (return string via :name, then call :demodulize)
0

It's quite simple.

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

5 Comments

It's better to split on "::". End result is the same, but reveals intention better.
why, if the single colon doesn't appear anywhere else in the name?
Result of splitting on "::" can be used for a couple of other tasks. Result of splitting on ":" is useless (except for this case) because of the empty strings in it.
yes, but I'm not initializing this array or using it for anything else.
Anyhow, the separator here is "::", not ":". Benefit of not using full separator is unclear to me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.