Class: Feature::ConstantLookup

Inherits:
Object
  • Object
show all
Defined in:
lib/toggles/constant_lookup.rb

Constant Summary collapse

Error =
Class.new(NameError) do
  attr_reader :sym

  def initialize(sym)
    @sym = sym
    super(sym.join('::'))
  end
end

Class Method Summary collapse

Class Method Details

.from(features, path) ⇒ Object

Return a tree walker that translates Module#const_missing(sym) into the next child node

So Features::Cat::BearDog walks as:

  • next_features = Feature.features # root

  • const_missing(:Cat) => next_features = next_features

  • const_missing(:BearDog) => next_features

  • const_missing(:CN22) => next_features

Defined at Toggles.features_dir + “/cat/bear_dog.yaml”

Raises:

  • (Error)

    if constant cannot be resolved



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/toggles/constant_lookup.rb', line 22

def self.from(features, path)
  Class.new {
    class << self
      attr_accessor :features, :path

      def const_missing(sym)
        # translate class name into path part i.e :BearDog #=> 'bear_dog'
        key = sym.to_s
        key.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2'.freeze)
        key.gsub!(/([a-z\d])([A-Z])/, '\1_\2'.freeze)
        key.downcase!

        subtree_or_feature = features.fetch(key.to_sym)

        if subtree_or_feature.is_a?(Hash)
          Feature::ConstantLookup.from(subtree_or_feature, path + [sym])
        else
          subtree_or_feature
        end
      rescue KeyError
        raise Error, path + [sym]
      end
    end
  }.tap do |resolver|
    resolver.features = features
    resolver.path = path
  end
end