17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

インスタンスから名前空間を取得する

Last updated at Posted at 2014-09-11

やりたいこと

インスタンスのクラス名の名前空間の部分だけ抽出したい。
(例えば A::B::C::DA::B::C の部分)

方法

String#deconstantizeString#constantize を使って実現できます。 (Special thanks to @jkr_2255)

module Puella
  module Magi
    class HolyQuintet
      def initialize(name)
        @name = name
      end
    end
  end
end

instance = Puella::Magi::HolyQuintet.new("美樹さやか")
#=> #<Puella::Magi::HolyQuintet @name="美樹さやか">

class_name = instance.class.name
#=> "Puella::Magi::HolyQuintet"

class_name.deconstantize
#=> "Puella::Magi"

class_name.deconstantize.constantize
#=> Puella::Magi

以前 (2014/09/11 (木)) 紹介していた方法

String#demodulizeString#gsub を使えば簡単にできるよ!

module Puella
  module Magi
    class HolyQuintet
      def initialize(name)
        @name = name
      end
    end
  end
end

# Active Support Core Extensions が提供している String#demodulize を利用するため。
require 'active_support/core_ext'

instance = Puella::Magi::HolyQuintet.new("美樹さやか")
#=> #<Puella::Magi::HolyQuintet @name="美樹さやか">

class_name = instance.class.name
#=> "Puella::Magi::HolyQuintet"

class_name.demodulize
#=> "HolyQuintet"

# 名前空間の文字列を取得する。
class_name.gsub("::#{class_name.demodulize}", "")
#=> "Puella::Magi"

# 名前空間の Module (or Class) を取得する。
class_name.gsub("::#{class_name.demodulize}", "").constantize
#=> Puella::Magi
17
17
2

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
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?