user2012677
user2012677

Reputation: 5735

get class name of the immediate class, not full class name. ruby

module A
  module B
    class C < A::Base

    def some_method

    end
    end
  end
end

How do I get the class name "C" as when I refer to the class name, with .name, I get A::B::C

Upvotes: 3

Views: 199

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

In Rails you can do it as: A::B::C.name.demodulize.

Example:

Loading development environment (Rails 4.2.7.1)
[1] pry(main)> module A
[1] pry(main)*   class Base;end
[1] pry(main)*   module B
[1] pry(main)*     class C < A::Base
[1] pry(main)*
[1] pry(main)*       def some_method
[1] pry(main)*
[1] pry(main)*       end
[1] pry(main)*     end
[1] pry(main)*   end
[1] pry(main)* end
=> :some_method
[2] pry(main)> A::B::C.name.demodulize
=> "C"
[3] pry(main)>

Look at the documentation of #demodulize

Removes the module part from the constant expression in the string.

Upvotes: 5

Related Questions