Class: Mu::Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/mu/hash.rb,
lib/mu/hash/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value = {}) ⇒ Hash

Returns a new instance of Hash.



9
10
11
# File 'lib/mu/hash.rb', line 9

def initialize(value = {})
  self.value = value
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/mu/hash.rb', line 13

def method_missing(key)
  super unless is_a_dictionary?

  stringified_key = key.to_s
  unless value.keys.include?(stringified_key)
    raise Error.new("Key #{stringified_key} doesn't exist at the current path.")
  end

  new_value = value[stringified_key]

  # returning the wrapped sub hash to allow nested chaining
  wrap(new_value)
end

Instance Attribute Details

#valueObject

Returns the value of attribute value.



7
8
9
# File 'lib/mu/hash.rb', line 7

def value
  @value
end

Instance Method Details

#[](key) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mu/hash.rb', line 50

def [](key)
  if value.kind_of?(Array) && key.kind_of?(Numeric)
    if key >= value.length
      raise Error.new("Can't access index #{key} on a list of #{value.length} items.")
    end

    new_value = value[key]
    wrap(new_value)
  else
    self.send(key)
  end
end

#eachObject



27
28
29
30
31
32
33
# File 'lib/mu/hash.rb', line 27

def each
  return super unless value.kind_of?(Array)

  value.each do |item|
    yield wrap(item)
  end
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
# File 'lib/mu/hash.rb', line 43

def has_key?(key)
  return false unless is_a_dictionary?

  stringified_key = key.to_s
  value.keys.include?(stringified_key)
end

#mapObject



35
36
37
38
39
40
41
# File 'lib/mu/hash.rb', line 35

def map
  return super unless value.kind_of?(Array)

  value.map do |item|
    yield wrap(item)
  end
end

#unwrapObject



63
64
65
# File 'lib/mu/hash.rb', line 63

def unwrap
  self.value
end