Rails, how can I check if a class exists before it is created?

I have a utility class defined using the class method class. In the Rails console, when I search for a class using Object.const_defined?, it returns false. But after calling one of the methods of the class or creating an instance of the class, Object.const_defined?returns true. Is it because of some lazy instance loading? Is there any other way to check for a class that will return true, even if I haven't created anything yet?

+4
source share
2 answers

This is a kind of hack, but it works

Object.const_get(:ClassName).is_a?(Class) rescue false

The above statement will return true if the class is defined and returns false otherwise

+5
source

safe_constantize.

  your_class = "YourClassName".safe_constantize
  if your_class && your_class.class == Class
    your_class.new(options).run
  end
+6

Source: https://habr.com/ru/post/1525687/


All Articles