Class: NRSER::Config

Inherits:
Object show all
Includes:
Hamster::Associable, Hamster::Enumerable, Hamster::Immutable
Defined in:
lib/nrser/labs/config.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*sources) ⇒ Config

Instantiate a new ‘Config`.



77
78
79
80
81
82
83
# File 'lib/nrser/labs/config.rb', line 77

def initialize *sources
  @sources = sources
  @trie = sources.reduce( Hamster::EmptyTrie ) { |trie, source|
    self.class.deep_trie_merge trie, source
  }

end

Class Method Details

.deep_trie_merge(trie, source, &block) ⇒ Object

Class Methods



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/nrser/labs/config.rb', line 48

def self.deep_trie_merge trie, source, &block
  to_put = {}

  source.each_pair do |key, source_value|
    _, trie_value = trie.get key

    to_put[ key ] = if [ trie_value, source_value ].all? { |value|
      NRSER.hash_like?( value ) && value.respond_to?( :deep_merge )
    }
      trie_value.deep_merge source_value, &block
    elsif block
      block.call key, trie_value, source_value
    else
      source_value
    end
  end

  trie.bulk_put to_put
end

Instance Method Details

#each(*args, &block) ⇒ Object



153
154
155
# File 'lib/nrser/labs/config.rb', line 153

def each *args, &block
  @trie.each *args, &block
end

#get(*key_path, type: nil, default: nil) ⇒ Object Also known as: [], dig

Retrieve the value corresponding to the provided key object. If not found, and this ‘Hash` has a default block, the default block is called to provide the value. Otherwise, return `nil`.

Examples:

h = Hamster::Hash["A" => 1, "B" => 2, "C" => 3]
h["B"]             # => 2
h.get("B")         # => 2
h.get("Elephant")  # => nil

# Hamster Hash with a default proc:
h = Hamster::Hash.new("A" => 1, "B" => 2, "C" => 3) { |key| key.size }
h.get("B")         # => 2
h.get("Elephant")  # => 8

Parameters:

Returns:



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/nrser/labs/config.rb', line 108

def get *key_path, type: nil, default: nil
  first, *rest = key_path
  entry = @trie.get first

  value = if entry
    current = entry[ 1 ]

    while !current.nil? && !rest.empty?
      first, *rest = rest

      current = if current.respond_to? :dig
        rest = [] # Short-circuit
        current.dig *rest

      elsif current.respond_to? :[]
        current[ first ]
      
      elsif current.respond_to? :get
        current.get first
      
      else
        rest = []
        default

      end
    end

    current

  else
    default
  end

  parse_and_check key_path, value, type: type

end

#parse_and_check(key_path, value, type: nil) ⇒ Object



148
149
150
# File 'lib/nrser/labs/config.rb', line 148

def parse_and_check key_path, value, type: nil
  return value if type.nil?
end