LoginSignup
12
9

More than 5 years have passed since last update.

[Ruby] クラスの存在を確認する

Posted at

「このgemが入っていれば使うけど、無ければ別のgemを捜す」ような処理で、クラスの存在を確認したい場面があり。とりあえず defined? を使えばそれっぽいことは出来るけど、定数なのかクラス名なのかを識別する必要があったりして面倒だったりもしたので、メソッド化してみた。

class Module
  def class_exists? class_name
    if const_defined?(class_name)
      const_get(class_name).is_a?(Class)
    else
      false
    end
  end
end
Module.class_exists?('CGI')
#=> false
require 'cgi'
Module.class_exists?('CGI')
#=> true

Moduleを汚したくなければユーティリティにしてconst_defined?const_getModuleからの呼び出し固定にしてもいいけど、この形にしておけば名前空間内での存在確認にも使えて便利かも。

class Foo
  class Bar
    # do something
  end
end

Foo.class_exists?('Bar')
#=> true
Foo.class_exists?('Hoge')
#=> false
12
9
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
12
9