Class: JsonProjection::Projector

Inherits:
Object
  • Object
show all
Defined in:
lib/json-projection/projector.rb

Instance Method Summary collapse

Constructor Details

#initialize(stream) ⇒ Projector

Initialize a new projector with a stream. The stream is consumed until the JSON structure it contains is finished.

stream

IO IO stream to read data from.

Returns nothing.



13
14
15
# File 'lib/json-projection/projector.rb', line 13

def initialize(stream)
  @parser = Parser.new(stream)
end

Instance Method Details

#project(schema) ⇒ Object

Given a JSON schema of properties we are interested in, filter the input stream to just these properties.

Note this is not a schema validator, the schema is navigated to determine interesting-ness but if you specify a schema for a key that turns out to be a number it _will be included_. The projection only cares about whether things are interesting while advancing through the stream. To validate the schema, use another class on the resulting projection.

schema

nil | Hash<String, schema> Map of the keys we are interested in, recurses.

Returns a Hash<String, Any> instance or raises a parser error.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/json-projection/projector.rb', line 30

def project(schema)
  event = @parser.next_event
  unless event.is_a?(StartDocument)
    raise StandardError, "expected document start"
  end

  value = filter_subtree(schema, next_event)

  event = @parser.next_event
  unless event.is_a?(EndDocument)
    raise StandardError, "expected document end"
  end

  value
end