Class: Miasma::Utils::Smash

Inherits:
Hash
  • Object
show all
Includes:
Hashie::Extensions::Coercion, Hashie::Extensions::DeepMerge, Hashie::Extensions::IndifferentAccess, Hashie::Extensions::MergeInitializer
Defined in:
lib/miasma/utils/smash.rb

Overview

Customized Hash

Instance Method Summary collapse

Methods inherited from Hash

#to_smash

Constructor Details

#initialize(*args) ⇒ Smash

Create new instance

Parameters:

  • args (Object)

    argument list



20
21
22
23
24
25
26
27
28
29
# File 'lib/miasma/utils/smash.rb', line 20

def initialize(*args)
  base = nil
  if(args.first.is_a?(::Hash))
    base = args.shift
  end
  super *args
  if(base)
    self.replace(base.to_smash)
  end
end

Instance Method Details

#checksumString

Calculate checksum of hash (sha256)

Returns:

  • (String)

    checksum



90
91
92
# File 'lib/miasma/utils/smash.rb', line 90

def checksum
  Digest::SHA256.hexdigest(self.to_smash(:sorted).to_s)
end

#fetch(*args) ⇒ Object

Fetch value at given path or return a default value

Parameters:

  • args (String, Symbol, Object)

    key path to walk. last value default to return

Returns:

  • (Object)

    value at key or default value



55
56
57
58
# File 'lib/miasma/utils/smash.rb', line 55

def fetch(*args)
  default_value = args.pop
  retrieve(*args) || default_value
end

#merge!(hash) ⇒ Object



31
32
33
34
# File 'lib/miasma/utils/smash.rb', line 31

def merge!(hash)
  hash = hash.to_smash
  super(hash)
end

#retrieve(*args) ⇒ Object, NilClass Also known as: get

Get value at given path

Parameters:

  • args (String, Symbol)

    key path to walk

Returns:

  • (Object, NilClass)


40
41
42
43
44
45
46
47
48
# File 'lib/miasma/utils/smash.rb', line 40

def retrieve(*args)
  args.inject(self) do |memo, key|
    if(memo.is_a?(Hash))
      memo.to_smash[key]
    else
      nil
    end
  end
end

#set(*args) ⇒ Object

Set value at given path

Parameters:

  • args (String, Symbol, Object)

    key path to walk. set last value to given path

Returns:

  • (Object)

    value set



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/miasma/utils/smash.rb', line 64

def set(*args)
  unless(args.size > 1)
    raise ArgumentError.new 'Set requires at least one key and a value'
  end
  value = args.pop
  set_key = args.pop
  leaf = args.inject(self) do |memo, key|
    unless(memo[key].is_a?(Hash))
      memo[key] = Smash.new
    end
    memo[key]
  end
  leaf[set_key] = value
  value
end

#to_hash(*args) ⇒ Hash

Convert to Hash

Returns:



83
84
85
# File 'lib/miasma/utils/smash.rb', line 83

def to_hash(*args)
  self.to_type_converter(::Hash, :to_hash, *args)
end