Sha256: 8603f61d828506a61655168284cceae7142756d3734d03fb4ebe5e267e8b9ec2

Contents?: true

Size: 1.39 KB

Versions: 12

Compression:

Stored size: 1.39 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.new
        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 = string.encode(
          'UTF-8',
          'binary',
          invalid: :replace,
          undef: :replace,
          replace: ''
        )
        string
      end

    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
eancom-1.5.7 lib/eancom/parser/document.rb
eancom-1.5.6 lib/eancom/parser/document.rb
eancom-1.5.5 lib/eancom/parser/document.rb
eancom-1.5.4 lib/eancom/parser/document.rb
eancom-1.5.2 lib/eancom/parser/document.rb
eancom-1.5.1 lib/eancom/parser/document.rb
eancom-1.5.0 lib/eancom/parser/document.rb
eancom-1.4.0 lib/eancom/parser/document.rb
eancom-1.3.0 lib/eancom/parser/document.rb
eancom-1.2.0 lib/eancom/parser/document.rb
eancom-1.1.1 lib/eancom/parser/document.rb
eancom-1.1.0 lib/eancom/parser/document.rb