|
| 1 | +module RSpec |
| 2 | + module Support |
| 3 | + # Provides recursive constant lookup methods useful for |
| 4 | + # constant stubbing. |
| 5 | + module RecursiveConstMethods |
| 6 | + # We only want to consider constants that are defined directly on a |
| 7 | + # particular module, and not include top-level/inherited constants. |
| 8 | + # Unfortunately, the constant API changed between 1.8 and 1.9, so |
| 9 | + # we need to conditionally define methods to ignore the top-level/inherited |
| 10 | + # constants. |
| 11 | + # |
| 12 | + # Given: |
| 13 | + # class A; B = 1; end |
| 14 | + # class C < A; end |
| 15 | + # |
| 16 | + # On 1.8: |
| 17 | + # - C.const_get("Hash") # => ::Hash |
| 18 | + # - C.const_defined?("Hash") # => false |
| 19 | + # - C.constants # => ["B"] |
| 20 | + # - None of these methods accept the extra `inherit` argument |
| 21 | + # On 1.9: |
| 22 | + # - C.const_get("Hash") # => ::Hash |
| 23 | + # - C.const_defined?("Hash") # => true |
| 24 | + # - C.const_get("Hash", false) # => raises NameError |
| 25 | + # - C.const_defined?("Hash", false) # => false |
| 26 | + # - C.constants # => [:B] |
| 27 | + # - C.constants(false) #=> [] |
| 28 | + if Module.method(:const_defined?).arity == 1 |
| 29 | + def const_defined_on?(mod, const_name) |
| 30 | + mod.const_defined?(const_name) |
| 31 | + end |
| 32 | + |
| 33 | + def get_const_defined_on(mod, const_name) |
| 34 | + if const_defined_on?(mod, const_name) |
| 35 | + return mod.const_get(const_name) |
| 36 | + end |
| 37 | + |
| 38 | + raise NameError, "uninitialized constant #{mod.name}::#{const_name}" |
| 39 | + end |
| 40 | + |
| 41 | + def constants_defined_on(mod) |
| 42 | + mod.constants.select { |c| const_defined_on?(mod, c) } |
| 43 | + end |
| 44 | + else |
| 45 | + def const_defined_on?(mod, const_name) |
| 46 | + mod.const_defined?(const_name, false) |
| 47 | + end |
| 48 | + |
| 49 | + def get_const_defined_on(mod, const_name) |
| 50 | + mod.const_get(const_name, false) |
| 51 | + end |
| 52 | + |
| 53 | + def constants_defined_on(mod) |
| 54 | + mod.constants(false) |
| 55 | + end |
| 56 | + end |
| 57 | + |
| 58 | + def recursive_const_get(const_name) |
| 59 | + normalize_const_name(const_name).split('::').inject(Object) do |mod, name| |
| 60 | + get_const_defined_on(mod, name) |
| 61 | + end |
| 62 | + end |
| 63 | + |
| 64 | + def recursive_const_defined?(const_name) |
| 65 | + normalize_const_name(const_name).split('::').inject([Object, '']) do |(mod, full_name), name| |
| 66 | + yield(full_name, name) if block_given? && !(Module === mod) |
| 67 | + return false unless const_defined_on?(mod, name) |
| 68 | + [get_const_defined_on(mod, name), [mod, name].join('::')] |
| 69 | + end |
| 70 | + end |
| 71 | + |
| 72 | + def normalize_const_name(const_name) |
| 73 | + const_name.sub(/\A::/, '') |
| 74 | + end |
| 75 | + end |
| 76 | + end |
| 77 | +end |
0 commit comments