Class: Plutonium::Lib::OverlayedHash

Inherits:
Object
  • Object
show all
Defined in:
lib/plutonium/lib/overlayed_hash.rb

Overview

OverlayedHash provides a hash-like structure that overlays values on top of a base hash.

This class allows you to create a new hash-like object that uses a base hash for default values, but can be modified without affecting the original base hash. When a key is accessed, it first checks if the key exists in the overlay; if not, it falls back to the base hash.

Examples:

Usage

base = { a: 1, b: 2 }
overlay = OverlayedHash.new(base)
overlay[:b] = 3
overlay[:c] = 4

overlay[:a] # => 1 (from base)
overlay[:b] # => 3 (from overlay)
overlay[:c] # => 4 (from overlay)
base[:b]    # => 2 (unchanged)

Instance Method Summary collapse

Constructor Details

#initialize(base) ⇒ OverlayedHash

Initialize a new OverlayedHash with a base hash.



25
26
27
28
# File 'lib/plutonium/lib/overlayed_hash.rb', line 25

def initialize(base)
  @base = base
  @overlay = {}
end

Instance Method Details

#[](key) ⇒ Object

Retrieve a value from the overlay hash or the base hash.



34
35
36
# File 'lib/plutonium/lib/overlayed_hash.rb', line 34

def [](key)
  @overlay.key?(key) ? @overlay[key] : @base[key]
end

#[]=(key, value) ⇒ Object

Set a value in the overlay hash.



42
43
44
# File 'lib/plutonium/lib/overlayed_hash.rb', line 42

def []=(key, value)
  @overlay[key] = value
end

#each_key {|key| ... } ⇒ Enumerator

Enumerate over all keys in both the overlay and base hash.

Yields:

  • (key)

    Gives each key to the block.



58
59
60
61
62
# File 'lib/plutonium/lib/overlayed_hash.rb', line 58

def each_key
  return to_enum(:each_key) unless block_given?

  keys.each { |key| yield key }
end

#key?(key) ⇒ Boolean

Check if a key exists in either the overlay or base hash.



50
51
52
# File 'lib/plutonium/lib/overlayed_hash.rb', line 50

def key?(key)
  @overlay.key?(key) || @base.key?(key)
end

#keysArray

Retrieve all keys from both the overlay and base hash.



67
68
69
# File 'lib/plutonium/lib/overlayed_hash.rb', line 67

def keys
  (@overlay.keys + @base.keys).uniq
end

#to_hHash

Convert the OverlayedHash to a regular Hash.



81
82
83
# File 'lib/plutonium/lib/overlayed_hash.rb', line 81

def to_h
  keys.each_with_object({}) { |key, hash| hash[key] = self[key] }
end

#valuesArray

Retrieve all values, prioritizing the overlay over the base.



74
75
76
# File 'lib/plutonium/lib/overlayed_hash.rb', line 74

def values
  keys.map { |key| self[key] }
end