Module: Pru
- Defined in:
- lib/pru.rb,
lib/pru/version.rb
Constant Summary collapse
- VERSION =
"0.3.0"
Class Method Summary collapse
-
.each_json(io) ⇒ Object
An enumerable of JSON values parsed from a stream (newline-delimited or multiline), parsed lazily so we process as input arrives, by accumulating lines until the buffer forms a complete value.
- .map(items, code) ⇒ Object
- .reduce(array, code) ⇒ Object
Class Method Details
.each_json(io) ⇒ Object
An enumerable of JSON values parsed from a stream (newline-delimited or multiline), parsed lazily so we process as input arrives, by accumulating lines until the buffer forms a complete value. TODO: this is not very efficient, but keeping track of opening/closing braces might be ugly too
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/pru.rb', line 28 def each_json(io) Enumerator.new do |yielder| buffer = +"" io.each_line do |line| buffer << line begin item = JSON.parse(buffer) rescue JSON::ParserError next end yielder << item buffer = +"" end raise JSON::ParserError, "unexpected trailing input: #{buffer.strip}" unless buffer.strip.empty? end end |
.map(items, code) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/pru.rb', line 5 def map(items, code) block = compile(code) i = 0 items.each do |item| i += 1 result = item.instance_exec(i, &block) || next case result when true then yield item when Regexp then yield item if item =~ result else yield result end end end |
.reduce(array, code) ⇒ Object
20 21 22 |
# File 'lib/pru.rb', line 20 def reduce(array, code) array.instance_exec(&compile(code)) end |