Class | Module |
In: |
lib/extlib/module.rb
|
Parent: | Object |
# File lib/extlib/module.rb, line 2 2: def find_const(const_name) 3: if const_name[0..1] == '::' 4: Object.full_const_get(const_name[2..-1]) 5: else 6: nested_const_lookup(const_name) 7: end 8: end
Doesn‘t do any caching since constants can change with remove_const
# File lib/extlib/module.rb, line 17 17: def nested_const_lookup(const_name) 18: unless equal?(Object) 19: constants = [] 20: 21: name.split('::').each do |part| 22: const = constants.last || Object 23: constants << const.const_get(part) 24: end 25: 26: parts = const_name.split('::') 27: 28: # from most to least specific constant, use each as a base and try 29: # to find a constant with the name const_name within them 30: constants.reverse_each do |const| 31: # return the nested constant if available 32: return const if parts.all? do |part| 33: const = if RUBY_VERSION >= '1.9.0' 34: const.const_defined?(part, false) ? const.const_get(part, false) : nil 35: else 36: const.const_defined?(part) ? const.const_get(part) : nil 37: end 38: end 39: end 40: end 41: 42: # no relative constant found, fallback to an absolute lookup and 43: # use const_missing if not found 44: Object.full_const_get(const_name) 45: end