Class: Hash::Normalized

Inherits:
Hash
  • Object
show all
Includes:
DeepFreezable
Defined in:
lib/hash_ext/normalized.rb

Direct Known Subclasses

Indifferent

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DeepFreezable

#deep_freeze

Constructor Details

#initialize(hash = {}, &block) ⇒ Normalized

Returns a new instance of Normalized.



14
15
16
17
# File 'lib/hash_ext/normalized.rb', line 14

def initialize(hash={}, &block)
  @normalization_block = block
  update hash
end

Class Method Details

.subclass(&block) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/hash_ext/normalized.rb', line 6

def self.subclass(&block)
  Class.new(self) do
    define_method :initialize do |hash={}|
      super hash, &block
    end
  end
end

Instance Method Details

#[](key) ⇒ Object



19
20
21
# File 'lib/hash_ext/normalized.rb', line 19

def [](key)
  super normalize_key(key)
end

#[]=(key, value) ⇒ Object Also known as: store



23
24
25
# File 'lib/hash_ext/normalized.rb', line 23

def []=(key, value)
  super normalize_key(key), normalize_value(value)
end

#delete(key) ⇒ Object



28
29
30
# File 'lib/hash_ext/normalized.rb', line 28

def delete(key)
  super normalize_key(key)
end

#dig(*keys) ⇒ Object



56
57
58
59
60
61
# File 'lib/hash_ext/normalized.rb', line 56

def dig(*keys)
  normalized_keys = keys.map { |k| normalize_key(k) }
  normalized_keys.inject(self) do |target, key|
    target ? target[key] : nil
  end
end

#fetch(key, *args, &block) ⇒ Object



52
53
54
# File 'lib/hash_ext/normalized.rb', line 52

def fetch(key, *args, &block)
  super normalize_key(key), *args, &block
end

#key?(key) ⇒ Boolean Also known as: include?, has_key?, member?

Returns:

  • (Boolean)


45
46
47
# File 'lib/hash_ext/normalized.rb', line 45

def key?(key)
  super normalize_key(key)
end

#merge(hash, &block) ⇒ Object



41
42
43
# File 'lib/hash_ext/normalized.rb', line 41

def merge(hash, &block)
  dup.update hash, &block
end

#to_hObject



63
64
65
66
67
# File 'lib/hash_ext/normalized.rb', line 63

def to_h
  each_with_object({}) do |(key, value), hash|
    hash[key] = value_to_h value
  end
end

#update(hash, &block) ⇒ Object Also known as: merge!



32
33
34
35
36
37
38
# File 'lib/hash_ext/normalized.rb', line 32

def update(hash, &block)
  hash.each do |key, value|
    new_val = block && key?(key) ? block.call(key, self[key], value) : value
    store key, new_val
  end
  self
end