Sha256: a1a9d4ca601ff746433aabdc922ce7e86201a39d1e2939c0c29fb90ac318e843

Contents?: true

Size: 1.09 KB

Versions: 4

Compression:

Stored size: 1.09 KB

Contents

class FixedWidth
  class Parser
    def initialize(definition, file)
      @definition = definition
      @file       = file
    end

    def parse
      @parsed = {}
      @content = read_file
      unless @content.empty?
        @definition.sections.each do |section|
          rows = fill_content(section)
          raise FixedWidth::RequiredSectionNotFoundError.new("Required section '#{section.name}' was not found.") unless rows > 0 || section.optional
        end
      end
      @parsed
    end

    private

    def read_file
      @file.readlines.map(&:chomp)
    end

    def fill_content(section)
      matches = 0
      loop do
        line = @content.first
        break unless section.match(line)
        add_to_section(section, line)
        matches += 1
        @content.shift
      end
      matches
    end

    def add_to_section(section, line)
      if section.singular
        @parsed[section.name] = section.parse(line)
      else
        @parsed[section.name] ||= []
        @parsed[section.name] << section.parse(line)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
fixed_width-multibyte-0.2.3 lib/fixed_width/parser.rb
fixed_width-multibyte-0.2.2 lib/fixed_width/parser.rb
fixed_width-0.2.1 lib/fixed_width/parser.rb
fixed_width-0.2.0 lib/fixed_width/parser.rb