module Eancom module Edifact class Data class TypeError < StandardError; end class LengthError < StandardError; end class RequiredError < StandardError; end class NotFoundInDictionary < StandardError; end attr_accessor :type, :length, :dictionary, :description, :required def initialize(type:, length:, dictionary: nil, description:, required: ) @type = type @length = length @dictionary = dictionary @description = description @required = required end def valid?(key, value) type?(key, value) length?(key, value) required?(key, value) dictionary?(key, value) unless value.empty? end def identifier(value) if @dictionary hash = @dictionary[value] unless hash raise NotFoundInDictionary.new( "Value not found for #{value}. Error in Data: #{self.to_s}" ) else hash[:identifier] end else "" end end def to_s "type: #{@type} " \ "length: #{@length} " \ "dictionary: #{@dictionary} " \ "description: #{@description} " \ "required: #{required} " end private def type?(key, value) unless value.kind_of?(@type) raise TypeError.new( "Wrong type of #{key}: #{value}, should be #{@type}. Error in Data: #{self.to_s}" ) end end def length?(key, value) if @length.kind_of?(Range) unless @length.include?(value.length) raise LengthError.new( "The value #{key}: #{value} is not in the range of #{@length}. Error in Data: #{self.to_s}") end elsif @length.kind_of?(Integer) unless value.length == @length raise LengthError.new( "The length of #{key}: #{value} should be #{@length}. Error in Data: #{self.to_s}" ) end else raise LengthError.new( "Error in length definition. Error in Data: #{self.to_s}" ) end end def required?(key, value) unless (!@required || !value.nil?) raise RequiredError.new( "The field required. Error in #{self.to_s}" ) end end def dictionary?(key, value) unless @dictionary.nil? unless @dictionary.key?(value) if @dictionary.key?('*') # Bypass Validation return true else raise NotFoundInDictionary.new( "The value '#{key}: #{value}' is not in the dictionary. Error in #{self.to_s}" ) end end end end end end end