Module: Pru

Defined in:
lib/pru.rb,
lib/pru/version.rb

Constant Summary collapse

VERSION =
"0.3.1"

Class Method Summary collapse

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.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/pru.rb', line 27

def each_json(io)
  Enumerator.new do |yielder|
    buffer = +""
    io.each_line do |line|
      buffer << line
      # Only attempt a parse when the buffer could actually be complete: a JSON value's
      # last significant character is always '}', ']', '"', a digit, or 'e'/'l'
      # (true/false/null). Skipping impossible parses keeps a multi-line value O(n)
      # instead of re-parsing the whole growing buffer on every line.
      next unless /[}\]"\del]\z/.match?(buffer.rstrip)
      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