Class: ISO8583::BCDField

Inherits:
Field
  • Object
show all
Defined in:
lib/iso8583/field.rb

Instance Attribute Summary collapse

Attributes inherited from Field

#bmp, #codec, #max, #name, #padding

Instance Method Summary collapse

Methods inherited from Field

#parse

Instance Attribute Details

#byte_lengthObject

Returns the value of attribute byte_length.



89
90
91
# File 'lib/iso8583/field.rb', line 89

def byte_length
  @byte_length
end

#data_lengthObject

Returns the value of attribute data_length.



88
89
90
# File 'lib/iso8583/field.rb', line 88

def data_length
  @data_length
end

Instance Method Details

#encode(value) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/iso8583/field.rb', line 105

def encode(value)
  begin
    encoded_value = codec.encode(value)
    @data_length = value.to_s.size
    @byte_length = encoded_value.bytes.size
  rescue ISO8583Exception => e
    ContextLog.exception(e, e.backtrace, "#{e.message} (#{name})") if Object.const_defined?(:ContextLog)
    raise ISO8583Exception.new(e.message+" (#{name})")
  end

  if padding
    if padding.arity == 1
      encoded_value = padding.call(encoded_value)
    elsif padding.arity == 2
      encoded_value = padding.call(encoded_value, length)
    end
  end

  len_str = case length
            when Integer
              raise ISO8583Exception.new("Too long: #{value} (#{name})! length=#{length}")  if encoded_value.length > length
              raise ISO8583Exception.new("Too short: #{value} (#{name})! length=#{length}") if encoded_value.length < length
              String.new("", encoding: 'ASCII-8BIT')
            when Field
              raise ISO8583Exception.new("Max length exceeded: #{value}, max: #{max}") if max && @byte_length > max
              length.encode(@data_length)
            else
              raise ISO8583Exception.new("Invalid length (#{length}) for '#{name}' field")
            end

  len_str + encoded_value

end

#lengthObject

This corrects the length for BCD fields, as their encoded length is half (+ parity) of the content length. E.g. 123 (length = 3) encodes to “x01x23” (length 2)



92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/iso8583/field.rb', line 92

def length
  if @length.respond_to?(:odd?)
    @data_length = @length
    if @data_length.odd?
      @byte_length = (@data_length + 1) / 2
    else
      @byte_length = @data_length / 2
    end
    return @byte_length
  end
  @length
end