From: MIYAMUKO Katsuyuki Date: 2007-04-06T12:10:07+09:00 Subject: [ruby-list:43372] Re: 特定のmoduleに属しているかの判別 みやむこです。 > > Foo::Barクラスのインスタンスなりクラスなりから、 > > 「自分(Foo:Bar)はFoo配下のクラスである」と判別したいのです 別解として、ActiveSupport を使うという手もあります。 中でやっていることは [ruby-list:43364] とだいたい同じです。 require "active_support" module Foo class Bar class Baz p self.parent #=> Foo::Bar p self.parent == Foo::Bar #=> true p self.parents #=> [Foo::Bar, Foo, Object] p self.parents.include?(Foo) #=> true p self.parents.include?(Foo::Bar) #=> true end end end > $o.class.to_s.split(/::/)[0..-2].inject(Object){|s,x| s.const_get(x)} # => Foo::Bar > > injectとconst_getの連携は慣用句でしょう。 これ、そのクラスが存在するかしないか分からないような pluggable なスクリプトを書いてるときにはまるんですよね。 (というか、最近はまりました :-) class String def my_constantize split(/::/).inject(Object){|s,x| s.const_get(x)} end end module Plugin module Gmail; end end class Gmail; end class YouTube; end p "Plugin::Gmail".my_constantize # => Plugin::Gmail p "Plugin::YouTube".my_constantize # => YouTube # → Plugin::YouTube は存在しないのでエラーになってほしいが、 # ::YouTube が返ってくる。。。orz これも ActiveSupport で。 require "active_support" p "Plugin::Gmail".constantize # => Plugin::Gmail p "Plugin::YouTube".constantize # => #