Class: Phronomy::OutputParser::StructuredParser

Inherits:
Base
  • Object
show all
Defined in:
lib/phronomy/output_parser/structured_parser.rb

Overview

Parses JSON and maps it to an instance of the given schema class.

Examples:

PersonSchema = Struct.new(:name, :age, keyword_init: true)
parser = Phronomy::OutputParser::StructuredParser.new(PersonSchema)
parser.parse('{"name":"Alice","age":30}')  #=> #<struct PersonSchema name="Alice", age=30>

Instance Method Summary collapse

Methods inherited from Base

#invoke

Methods included from Runnable

#batch, #invoke, #stream, #trace

Constructor Details

#initialize(schema_class) ⇒ StructuredParser

Returns a new instance of StructuredParser.

Parameters:

  • schema_class (Class)

    Struct with keyword_init: true or equivalent



12
13
14
# File 'lib/phronomy/output_parser/structured_parser.rb', line 12

def initialize(schema_class)
  @schema_class = schema_class
end

Instance Method Details

#parse(text) ⇒ Object

Returns instance of schema_class.

Parameters:

  • text (String)

Returns:

  • (Object)

    instance of schema_class

Raises:



19
20
21
22
23
24
# File 'lib/phronomy/output_parser/structured_parser.rb', line 19

def parse(text)
  data = JsonParser.new.parse(text)
  @schema_class.new(**data)
rescue ArgumentError, TypeError => e
  raise Phronomy::ParseError, "Failed to map to schema: #{e.message}"
end