LoginSignup
6
7

More than 5 years have passed since last update.

名前空間を取り除いたクラス名を取得する

Posted at

Classクラスのclass_nameメソッドを使用すると取得できる。
と思ったら、class_nameはPryでしか使用できなかった。

どこで定義されているのかを調べてみたら、
yardモジュールで定義されていたようだった。

pry
[1] pry(main)> show-source Class.class_name

From: /Users/uchiko/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/yard-0.8.7.6/lib/yard/core_ext/module.rb @ line 7:
Owner: Module
Visibility: public
Number of lines: 3

def class_name
  name.split("::").last
end
[2] pry(main)>

ということで同じことをしたかったら、以下のようにすれば良さそう。

sample.rb
module Hoge
  class Fuga
    def name
      self.fullname.split('::').last
    end

    def fullname
      self.class.to_s
    end
  end
end

m = Hoge::Fuga.new
p m.name     #=> "Fuga"
p m.fullname #=> "Hoge::Fuga"
6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7