Sha256: 91341f0c748c078d7f6621b789476be8a8ba7bc4748044d6369bd8413e490491

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

module Eancom
  module Parser
    class Document
      class SegmentTypeNotDefined < StandardError; end

      attr_reader :file, :document

      def initialize(file:)
        @file = file
        @document = Eancom::Edifact::Document.new
      end

      def parse
        content.split(segment_delimiter).each do |segment_string|
          segment = Parser::Segment.new(segment_string)
          segment = segment.parse
          add(segment)
        end
        @document
      end

      private

      def add(segment)
        if segment.is_header?
          @document.add_to_header(segment)
        elsif segment.is_body?
          @document.add_to_body(segment)
        elsif segment.is_footer?
          @document.add_to_body(segment)
        else
          raise SegmentTypeNotDefined
        end
      end

      def content
        @content ||= begin
          @file.rewind
          string = convert(@file.read)
          string.delete!("\n")
          string.delete!("\r")
          string.chomp!
          string
        end
      end

      def composite_delimiter
        DELIMITERS[:data]
      end

      def segment_delimiter
        DELIMITERS[:segment]
      end

      def convert(string)
        string.encode('UTF-8')
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
eancom-2.0.0 lib/eancom/parser/document.rb