Module: Smush
- Defined in:
- lib/smush.rb,
lib/smush/version.rb
Constant Summary collapse
- VERSION =
"0.1.0"
Class Method Summary collapse
-
.bury!(hash, *args) ⇒ Object
Non monkey-patching version of proposed Hash#bury method.
- .smush(hash, key_stack = []) ⇒ Object
- .unsmush(smushed) ⇒ Object
Class Method Details
.bury!(hash, *args) ⇒ Object
Non monkey-patching version of proposed Hash#bury method
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/smush.rb', line 28 def bury!(hash, *args) if args.count < 1 raise ArgumentError.new("Requires a location to bury") elsif args.count < 2 raise ArgumentError.new("Requires a value to bury") elsif args.count == 2 hash[args[0]] = args[1] else arg = args.shift # Assume an integer key in the chain means it's an array if args.first.is_a?(Integer) hash[arg] ||= [] else hash[arg] ||= {} end bury!(hash[arg], *args) if args.any? hash end end |
.smush(hash, key_stack = []) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/smush.rb', line 5 def smush(hash, key_stack=[]) if hash.is_a?(Array) hash.map.with_index { |h, i| smush(h, key_stack + [i]) }.flatten elsif hash.is_a?(Hash) hash.inject([]) { |smushed, keyval| smushed + smush(keyval[1], key_stack + [keyval[0]]) } else [{ key: key_stack, value: hash }] end end |
.unsmush(smushed) ⇒ Object
19 20 21 22 23 24 25 |
# File 'lib/smush.rb', line 19 def unsmush(smushed) unsmushed = {} smushed.each { |h| bury!(unsmushed, *h[:key], h[:value]) } unsmushed end |