Class: Reality::Mash

Inherits:
Hash
  • Object
show all
Defined in:
lib/reality/mash.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from(hash) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/reality/mash.rb', line 66

def self.from(hash)
  result = Mash.new
  hash.each_pair do |k, v|
    result[k] = v.is_a?(Hash) ? Mash.from(v) : v
  end
  result
end

Instance Method Details

#[](key) ⇒ Object



20
21
22
23
# File 'lib/reality/mash.rb', line 20

def [](key)
  self.h_write(key, Mash.new) unless key?(key)
  self.h_read(key)
end

#h_readObject



17
# File 'lib/reality/mash.rb', line 17

alias_method :h_read, :[]

#merge(other) ⇒ Object



34
35
36
37
38
39
# File 'lib/reality/mash.rb', line 34

def merge(other)
  result = Mash.new
  result.merge!(self)
  result.merge!(other)
  result
end

#merge!(other) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/reality/mash.rb', line 41

def merge!(other)
  other.each_pair do |k, v|
    if v.is_a?(Hash)
      self[k].merge!(v)
    elsif v.is_a?(Array)
      if self.key?(k) && self[k].is_a?(Array)
        self[k] = self[k].concat(v)
      else
        self[k] = v.dup
      end
    else
      self[k] = v
    end
  end
end

#sortObject



57
58
59
60
61
62
63
64
# File 'lib/reality/mash.rb', line 57

def sort
  result = Mash.new
  self.keys.sort.each do |key|
    value = self[key]
    result[key] = value.is_a?(Mash) ? value.sort : value
  end
  result
end

#to_hObject



25
26
27
28
29
30
31
32
# File 'lib/reality/mash.rb', line 25

def to_h
  basic_types = [Integer, Float, TrueClass, FalseClass, NilClass]
  result = {}
  each_pair do |key, value|
    result[key] = value.is_a?(Mash) ? value.to_h : basic_types.include?(value.class) ? value : value.dup
  end
  result
end