Module: Extensions::RelativeConstGet

Included in:
ReactiveResource::Base
Defined in:
lib/reactive_resource/extensions/relative_const_get.rb

Overview

Supplies RelativeConstGet#relative_const_get, which is like const_get, except it attempts to resolve using the current class’s module, rather than the class’s scope itself.

Instance Method Summary collapse

Instance Method Details

#relative_const_get(name) ⇒ Object

Finds the constant with name name, relative to the calling module. For instance, A::B.const_get_relative("C") will search for A::C, then ::C. This is heavily inspired by find_resource_in_modules in active_resource.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/reactive_resource/extensions/relative_const_get.rb', line 11

def relative_const_get(name)
  module_names = self.name.split("::")
  if module_names.length > 1
    receiver = Object
    namespaces = module_names[0, module_names.size-1].map do |module_name|
      receiver = receiver.const_get(module_name)
    end
    const_args = RUBY_VERSION < "1.9" ? [name] : [name, false]
    if namespace = namespaces.reverse.detect { |ns| ns.const_defined?(*const_args) }
      return namespace.const_get(*const_args)
    else
      raise NameError, "Couldn't find a class named #{name}"
    end
  else
    const_get(name)
  end
end