Sha256: eb4e726b297145008a4e5fda4117f83f3bc1516872ecc00933fade705d3b836d

Contents?: true

Size: 1.64 KB

Versions: 3

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true

module Eancom
  module Edifact
    class Message
      attr_accessor :locations, :items, :hash

      def initialize
        @locations = []
        @items = []
        @hash = {}
      end

      def add_location(location)
        @locations << location
      end

      def add_item(item)
        @items << item
      end

      def <<(segment)
        start_location if segment.starts_location?
        start_item if segment.starts_item?

        if @location
          @location << segment
        elsif @item
          @item << segment
        elsif name = group_name(segment)
          @hash[name] = [] if @hash[name].nil?
          @hash[name] << segment.to_json_hash
        else
          @hash.merge!(segment.to_json_hash)
        end
      end

      def to_json_hash
        if @location && !@location.empty?
          add_location(@location.to_json_hash)
        end
        if @item && !@item.empty?
          add_item(@item.to_json_hash)
        end
        message_hash = {}
        message_hash.merge!(@hash)
        message_hash.merge!({ locations: @locations }) if !@locations.empty?
        message_hash.merge!({ items: @items }) if !@items.empty?
        message_hash
      end

      private

      def group_name(segment)
        segment.group_name
      end

      def start_location
        if @location && !@location.empty?
          add_location(@location.to_json_hash)
        end
        @location = Eancom::Edifact::Location.new
      end

      def start_item
        if @item && !@item.empty?
          add_item(@item.to_json_hash)
        end
        @item = Eancom::Edifact::Item.new
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
eancom-1.6.3 lib/eancom/edifact/message.rb
eancom-1.6.2 lib/eancom/edifact/message.rb
eancom-1.6.0 lib/eancom/edifact/message.rb