Class: Carnivore::Utils::Smash
- Inherits:
-
Hash
- Object
- Hash
- Carnivore::Utils::Smash
- Includes:
- Hashie::Extensions::Coercion, Hashie::Extensions::DeepMerge, Hashie::Extensions::IndifferentAccess
- Defined in:
- lib/carnivore/utils/smash.rb
Overview
Customized Hash
Instance Method Summary (collapse)
-
- (Object) fetch(*args)
Fetch value at given path or return a default value.
-
- (Smash) initialize(*args)
constructor
Create new instance.
-
- (Object, NilClass) retrieve(*args)
(also: #get)
Get value at given path.
-
- (Object) set(*args)
Set value at given path.
Constructor Details
- (Smash) initialize(*args)
Create new instance
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
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
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
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 |