Class: Liquid2::ReadOnlyChainHash

Inherits:
Object
  • Object
show all
Defined in:
lib/liquid2/utils/chain_hash.rb

Overview

Combine multiple hashes for sequential lookup.

Instance Method Summary collapse

Constructor Details

#initialize(*hashes) ⇒ ReadOnlyChainHash

Returns a new instance of ReadOnlyChainHash.

Parameters:



7
8
9
# File 'lib/liquid2/utils/chain_hash.rb', line 7

def initialize(*hashes)
  @hashes = hashes.to_a
end

Instance Method Details

#[](key) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/liquid2/utils/chain_hash.rb', line 11

def [](key)
  index = @hashes.length - 1
  while index >= 0
    h = @hashes[index]
    index -= 1
    return h[key] if h.key?(key)
  end
end

#fetch(key, default = :undefined) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/liquid2/utils/chain_hash.rb', line 24

def fetch(key, default = :undefined)
  index = @hashes.length - 1
  while index >= 0
    h = @hashes[index]
    index -= 1
    return h[key] if h.key?(key)
  end

  default
end

#key?(key) ⇒ Boolean

Returns:



20
21
22
# File 'lib/liquid2/utils/chain_hash.rb', line 20

def key?(key)
  !@hashes.rindex { |h| h.key?(key) }.nil?
end

#popObject



38
# File 'lib/liquid2/utils/chain_hash.rb', line 38

def pop = @hashes.pop

#push(hash) ⇒ Object Also known as: <<



36
# File 'lib/liquid2/utils/chain_hash.rb', line 36

def push(hash) = @hashes << hash

#sizeObject



35
# File 'lib/liquid2/utils/chain_hash.rb', line 35

def size = @hashes.length