Class: IMW::Parsers::LineParser

Inherits:
Object
  • Object
show all
Defined in:
lib/imw/parsers/line_parser.rb

Overview

This is an abstract class for a line-oriented parser intended to read and emit lines sequentially from a file.

To leverage the functionality of this class, subclass it and define a parse_line method.

Direct Known Subclasses

RegexpParser

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ LineParser

If called with the option :skip_first then skip the corresponding number of lines at the beginning of the file when parsing.



21
22
23
24
# File 'lib/imw/parsers/line_parser.rb', line 21

def initialize options={}
  @skip_first = options[:skip_first] || 0
  @klass      = options[:of]         || options[:klass]
end

Instance Attribute Details

#klassObject

The class to parse each line into. The new method of this class must accept a hash.



16
17
18
# File 'lib/imw/parsers/line_parser.rb', line 16

def klass
  @klass
end

#skip_firstObject

The number of lines to skip on each file parsed.



12
13
14
# File 'lib/imw/parsers/line_parser.rb', line 12

def skip_first
  @skip_first
end

Instance Method Details

#parse!(file, options = {}, &block) ⇒ Object

Parse the given file. If the option :lines is passed in then only parse that many lines. If given a block then yield the result of each line to the block; else just return an array of results.

If this parser has a klass attribute then each parsed line will first be turned into an instance of that class (the class must accept a hash of values in its initializer).



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/imw/parsers/line_parser.rb', line 34

def parse! file, options={}, &block
  skip_lines!(file)
  if options[:lines]
    case
    when klass && block_given?
      options[:lines].times do
        yield klass.new(parse_line(file.readline))
      end
    when block_given?
      options[:lines].times do
        yield parse_line(file.readline)
      end
    when klass
      options[:lines].times do
        klass.new(parse_line(file.readline))
      end
    else
      options[:lines].times.map do
        parse_line(file.readline)
      end
    end
  else
    case
    when klass && block_given?
      file.each do |line|
        yield klass.new(parse_line(line))
      end
    when block_given?
      file.each do |line|
        yield parse_line(line)
      end
    when klass
      file.map do |line|
        klass.new(parse_line(line))
      end
    else
      file.map do |line|
        parse_line(line)
      end
    end
  end
end

#parse_line(line) ⇒ Object



77
78
79
# File 'lib/imw/parsers/line_parser.rb', line 77

def parse_line line
  raise IMW::NotImplementedError.new("Subclass the LineParser and redefine this method to create a true parser.")
end