lib/eancom/edifact/segment.rb in eancom-0.1.0 vs lib/eancom/edifact/segment.rb in eancom-1.1.0
- old
+ new
@@ -1,26 +1,145 @@
module Eancom
module Edifact
class Segment
- attr_accessor :name, :composites
+ attr_accessor :tag
- def initialize(name = "")
- @name = name
- @composites = []
+ class SegmentParserError < StandardError; end
+
+ def initialize(tag:)
+ @tag = tag
+ validate_structure
end
- def composite(content = "")
- @composites << content
+ def self.initialize_by_components(structure, array)
+ begin
+ new(structure.build_hash(array))
+ rescue StandardError => e
+ raise SegmentParserError.new(
+ "'Parser Error in structure #{structure.tag} with array #{array}.\n \
+ 'Inside Structure: \n \ '#{structure.to_s}.\n \
+ 'Error:\n \
+ '#{e}"
+ )
+ end
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
- stream = ""
- stream << name
- @composites.each do |composite|
- stream << DELIMITERS[:data]
- stream << composite
+ 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
- stream
+ 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