Module: RSpec::Support::RecursiveConstMethods

Defined in:
lib/rspec/support/recursive_const_methods.rb

Overview

Provides recursive constant lookup methods useful for constant stubbing.

Instance Method Summary collapse

Instance Method Details

#const_defined_on?(mod, const_name) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/rspec/support/recursive_const_methods.rb', line 31

def const_defined_on?(mod, const_name)
  mod.const_defined?(const_name)
end

#constants_defined_on(mod) ⇒ Object



41
42
43
# File 'lib/rspec/support/recursive_const_methods.rb', line 41

def constants_defined_on(mod)
  mod.constants.select { |c| const_defined_on?(mod, c) }
end

#get_const_defined_on(mod, const_name) ⇒ Object

Raises:

  • (NameError)


35
36
37
38
39
# File 'lib/rspec/support/recursive_const_methods.rb', line 35

def get_const_defined_on(mod, const_name)
  return mod.const_get(const_name) if const_defined_on?(mod, const_name)

  raise NameError, "uninitialized constant #{mod.name}::#{const_name}"
end

#normalize_const_name(const_name) ⇒ Object



73
74
75
# File 'lib/rspec/support/recursive_const_methods.rb', line 73

def normalize_const_name(const_name)
  const_name.sub(/\A::/, '')
end

#recursive_const_defined?(const_name) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
67
68
69
70
71
# File 'lib/rspec/support/recursive_const_methods.rb', line 64

def recursive_const_defined?(const_name)
  parts = normalize_const_name(const_name).split('::')
  parts.inject([Object, '']) do |(mod, full_name), name|
    yield(full_name, name) if block_given? && !(Module === mod)
    return false unless const_defined_on?(mod, name)
    [get_const_defined_on(mod, name), [mod.name, name].join('::')]
  end
end

#recursive_const_get(const_name) ⇒ Object



58
59
60
61
62
# File 'lib/rspec/support/recursive_const_methods.rb', line 58

def recursive_const_get(const_name)
  normalize_const_name(const_name).split('::').inject(Object) do |mod, name|
    get_const_defined_on(mod, name)
  end
end