Class: ConstStricter::ConstResolver::ConstLookup

Inherits:
Object
  • Object
show all
Defined in:
lib/const_stricter/const_resolver.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConstLookup

Returns a new instance of ConstLookup.



37
38
39
# File 'lib/const_stricter/const_resolver.rb', line 37

def initialize
  @resolved_paths = []
end

Instance Attribute Details

#cacheObject

Returns the value of attribute cache.



35
36
37
# File 'lib/const_stricter/const_resolver.rb', line 35

def cache
  @cache
end

#resolved_pathsObject

Returns the value of attribute resolved_paths.



35
36
37
# File 'lib/const_stricter/const_resolver.rb', line 35

def resolved_paths
  @resolved_paths
end

Instance Method Details

#find_constant(namespace:, const_name:, inherit: false) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/const_stricter/const_resolver.rb', line 41

def find_constant(namespace:, const_name:, inherit: false)
  cache_key = { namespace:, const_name: }
  return @cache[cache_key] if @cache.key?(cache_key)

  resolved_paths << cache_key

  (namespace ? Object.const_get(namespace) : Object).const_get(const_name, inherit)
rescue NameError => e
  missing_name =
    if e.respond_to?(:missing_name)
      # activesupport/lib/active_support/core_ext/name_error.rb
      e.missing_name
    else
      e.message[/uninitialized constant (.+)$/, 1]
    end

  if missing_name != const_name &&
     !const_name.start_with?(missing_name) &&
     missing_name.delete_prefix("#{namespace}::") != const_name
    # срабатывание может быть вызвано не искомой константой,
    # а тем, что есть несвязанная ошибка в коде вызываемого класса/модуля
    raise
  end

  if namespace
    const_path = ConstName.new(ConstName.split(namespace))
    const_path.pop

    find_constant(namespace: const_path.full_name, const_name:, inherit:)
  end
end