Class: DuperVisor::Parser

Inherits:
Object
  • Object
show all
Includes:
Formats::Accessors
Defined in:
lib/dupervisor/parser.rb

Overview

This class is responsible for coordination of parsing attempts of a given contet with diffirent format parsers.

Defined Under Namespace

Classes: FormatNotFound, ParseError

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Formats::Accessors

#format_classes, #formats

Constructor Details

#initialize(body) ⇒ Parser

Returns a new instance of Parser.



15
16
17
# File 'lib/dupervisor/parser.rb', line 15

def initialize(body)
  self.content = Content.new(body: body)
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



13
14
15
# File 'lib/dupervisor/parser.rb', line 13

def content
  @content
end

#parse_errorsObject

Returns the value of attribute parse_errors.



13
14
15
# File 'lib/dupervisor/parser.rb', line 13

def parse_errors
  @parse_errors
end

Instance Method Details

#parse(input_format = nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/dupervisor/parser.rb', line 19

def parse(input_format = nil)
  self.parse_errors    = {}
  content.parse_result = nil
  formats_to_check = input_format ? [ formats[input_format] ] : format_classes
  formats_to_check.each do |format_class|
    format = format_class.format
    parse_result = try_format(format, format_class)
    if parse_result
      content.parse_result = parse_result
      content.format       = format
      break
    end
  end
  unless content.parse_result || parse_errors.empty?
    if input_format
      raise ParseError.new("Can not parse from format #{input_format}. Format exception:" +
                             parse_errors.values.map(&:inspect).join("\n"))
    else
      raise FormatNotFound.new('No suitable format detected. Query #parse_errors for specifics.')
    end
  end
  content
end

#try_format(format, format_class) ⇒ Object



43
44
45
46
47
48
# File 'lib/dupervisor/parser.rb', line 43

def try_format(format, format_class)
  format_class.from.call(content.body)
rescue *(format_class.errors) => e
  self.parse_errors[format] = e
  nil
end