Module: Siren::Walker
- Included in:
- JsonParser, Parser
- Defined in:
- lib/siren/walker.rb
Instance Method Summary collapse
-
#walk(data, &reviver) ⇒ Object
If there is a reviver function, we recursively walk the new structure, passing each name/value pair to the reviver function for possible transformation, starting with a temporary root object that holds the result in an empty key.
Instance Method Details
#walk(data, &reviver) ⇒ Object
If there is a reviver function, we recursively walk the new structure, passing each name/value pair to the reviver function for possible transformation, starting with a temporary root object that holds the result in an empty key. If there is not a reviver function, we simply return the result.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/siren/walker.rb', line 9 def walk(data, &reviver) data = parse(data) if String === data return data unless block_given? walker = lambda do |holder, key| value = holder[key] for_each = lambda do |k, val| v = walker.call(value, k) if v.nil? holder.delete(k) else value[k] = v end end value.each { |k,v| for_each.call(k,v) } if Hash === value value.each_with_index { |v,i| for_each.call(i,v) } if Array === value reviver.call(holder, key, value) end walker.call({"" => data}, "") end |