Class: Carnivore::Utils::Smash

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

Overview

Customized Hash

Instance Method Summary (collapse)

Constructor Details

- (Smash) initialize(*args)

Create new instance

Parameters:

  • args (Object)

    argument list



17
18
19
20
21
22
23
24
25
26
# File 'lib/carnivore/utils/smash.rb', line 17

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

Instance Method Details

- (Object) fetch(*args)

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



47
48
49
50
# File 'lib/carnivore/utils/smash.rb', line 47

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

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

Get value at given path

Parameters:

  • args (String, Symbol)

    key path to walk

Returns:

  • (Object, NilClass)


32
33
34
35
36
37
38
39
40
# File 'lib/carnivore/utils/smash.rb', line 32

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

- (Object) set(*args)

Set value at given path

Parameters:

  • args (String, Symbol, Object)

    key path to walk. set last value to given path

Returns:

  • (Object)

    value set



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/carnivore/utils/smash.rb', line 56

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