module Eancom module Edifact class Segment attr_accessor :tag class SegmentParserError < StandardError; end def initialize(tag:) @tag = tag validate_structure end def self.initialize_by_components(structure, array) new(**structure.build_hash(array)) rescue StandardError => e raise SegmentParserError, "'Parser Error in structure #{structure.tag} with array #{array}.\n \ 'Inside Structure: \n \ '#{structure}.\n \ 'Error:\n \ '#{e}" end def validate_structure attributes.each do |key, value| next if value.nil? structure.validate!(key, value) end end def array @array ||= structure.build_array(to_hash) end def structure @structure ||= Eancom.find_structure(tag: tag) end def to_s string = array.map do |e| e = e.compact next if e.empty? [e.join(component_delimiter)] end.join(data_delimiter) clean_end_string(string) string << segment_delimiter string end def to_edi to_s end def to_json_hash raise NotImplementedError end def segment_type raise NotImplementedError end def to_hash attributes end def is_header? segment_type == :header end def is_body? segment_type == :body end def is_footer? segment_type == :footer end def tag?(other) tag == other end def starts_message? false end def starts_item? false end def group_name nil end def item_group_name nil end private def data_delimiter DELIMITERS[:data] end def component_delimiter DELIMITERS[:component] end def segment_delimiter DELIMITERS[:segment] end def attributes hash = {} instance_variables.each do |var| key = var.to_s.delete('@').to_sym next if key == :structure next if key == :array value = instance_variable_get(var) hash[key] = value end hash end def find_identifier(key) dictionary = structure.find(key).dictionary var = instance_variable_get('@' + key.to_s) if dictionary[var] dictionary[var][:identifier] else var end end def clean_end_string(string) while (string[-1] == data_delimiter) string.chop! end string end end end end