Sha256: c84143e46a073342d381a91e056d89c47907346b6e2a069aa975e5bb7265698e

Contents?: true

Size: 1.51 KB

Versions: 2

Compression:

Stored size: 1.51 KB

Contents

# frozen_string_literal: true

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(header_only: false)
        content.split(segment_delimiter).each do |segment_string|
          segment = Parser::Segment.new(segment_string)

          if header_only && segment.segment_class::TYPE != :header
            next
          end

          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_footer(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',
          'binary',
          invalid: :replace,
          undef: :replace,
          replace: ''
        )
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
eancom-1.6.3 lib/eancom/parser/document.rb
eancom-1.6.2 lib/eancom/parser/document.rb