Class: Optimistic::Json::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/optimistic/json/parser.rb

Overview

The main parser class

Defined Under Namespace

Classes: InvalidToken, MissingParser

Constant Summary collapse

TOKENS =
{
  space: [" ", "\t", "\r", "\n"],
  array: ["["],
  object: ["{"],
  number: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "-"],
  string: ['"'],
  true: ["t"],
  false: ["f"],
  null: ["n"]
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger: nil) ⇒ Parser

Returns a new instance of Parser.



42
43
44
45
# File 'lib/optimistic/json/parser.rb', line 42

def initialize(logger: nil)
  @logger = logger || ::Logger.new($stdout)
  @parsers = setup_parsers
end

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



40
41
42
# File 'lib/optimistic/json/parser.rb', line 40

def logger
  @logger
end

#parsersObject

Returns the value of attribute parsers.



40
41
42
# File 'lib/optimistic/json/parser.rb', line 40

def parsers
  @parsers
end

Instance Method Details

#handle_remaining_tokens(tokens, data, remaining_tokens) ⇒ Object



61
62
63
# File 'lib/optimistic/json/parser.rb', line 61

def handle_remaining_tokens(tokens, data, remaining_tokens)
  logger.info({ tokens: tokens, data: data, remaining_tokens: remaining_tokens })
end

#parse(tokens) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/optimistic/json/parser.rb', line 47

def parse(tokens)
  ::MultiJson.load(tokens)
rescue ::MultiJson::ParseError => e
  result = parse_any(tokens, e)

  if result[:remainder].length.positive?
    logger.warn("Unable to parse the following JSON: #{result[:remainder]}")

    handle_remaining_tokens(tokens, result[:data], result[:remainder])
  end

  result[:data]
end