Module: RSpec::Mocks::RecursiveConstMethods

Included in:
Constant, ConstantMutator, ConstantMutator::BaseMutator
Defined in:
lib/rspec/mocks/mutate_const.rb

Overview

Provides recursive constant lookup methods useful for constant stubbing.

Instance Method Summary (collapse)

Instance Method Details

- (Boolean) const_defined_on?(mod, const_name)



31
32
33
# File 'lib/rspec/mocks/mutate_const.rb', line 31

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

- (Object) constants_defined_on(mod)



43
44
45
# File 'lib/rspec/mocks/mutate_const.rb', line 43

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

- (Object) get_const_defined_on(mod, const_name)

Raises:

  • (NameError)


35
36
37
38
39
40
41
# File 'lib/rspec/mocks/mutate_const.rb', line 35

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

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

- (Object) normalize_const_name(const_name)



74
75
76
# File 'lib/rspec/mocks/mutate_const.rb', line 74

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

- (Boolean) recursive_const_defined?(const_name)



66
67
68
69
70
71
72
# File 'lib/rspec/mocks/mutate_const.rb', line 66

def recursive_const_defined?(const_name)
  normalize_const_name(const_name).split('::').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].join('::')]
  end
end

- (Object) recursive_const_get(const_name)



60
61
62
63
64
# File 'lib/rspec/mocks/mutate_const.rb', line 60

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