I have a utility class defined with a bunch of class methods. In the Rails console, when I search for the class using Object.const_defined?
it returns false. But after calling one of the class methods or creating an instance of the class, Object.const_defined?
returns true. Is this because of some kind of lazy loading instantiation kind of thing? Is there another way I can check for the existence of a class which will return true, even if I haven't instantiated anything yet?
Asked
Active
Viewed 3,506 times
4

zako42
- 634
- 9
- 16
-
You might just try eager-loading them; if the class hasn't been loaded, it hasn't been loaded, e.g., http://stackoverflow.com/q/19839847/438992 – Dave Newton Feb 06 '14 at 20:49
2 Answers
7
This is kind of a hack, but it works
Object.const_get(:ClassName).is_a?(Class) rescue false
Above statement will return true if the class is defined and return false otherwise

usha
- 28,973
- 5
- 72
- 93
-
4
-
-
1
-
I am wondering if there is a way to do this without exception handling? – Tigraine Dec 15 '14 at 13:42
6
You can use safe_constantize.
your_class = "YourClassName".safe_constantize
if your_class && your_class.class == Class
your_class.new(options).run
end

zzbazza
- 61
- 1
- 1