Method: Barcode1DTools::MSI.decode

Defined in:
lib/barcode1dtools/msi.rb

.decode(str, options = {}) ⇒ Object

Decode a string in rle format. This will return a MSI object.



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/barcode1dtools/msi.rb', line 171

def decode(str, options = {})
  if str =~ /[^1-3]/ && str =~ /[^wn]/
    raise UnencodableCharactersError, "Pattern must be rle or wn"
  end

  # ensure a wn string
  if str =~ /[1-3]/
    str = str.tr('123','nww')
  end

  if str.reverse =~ /\A#{GUARD_PATTERN_LEFT_WN}.*?#{GUARD_PATTERN_RIGHT_WN}\z/
    str.reverse!
  end

  unless str =~ /\A#{GUARD_PATTERN_LEFT_WN}(.*?)#{GUARD_PATTERN_RIGHT_WN}\z/
    raise UnencodableCharactersError, "Start/stop pattern is not detected."
  end

  wn_pattern = $1

  # Each pattern is 4 bars and 4 spaces, with a space between.
  unless wn_pattern.size % 8 == 0
    raise UnencodableCharactersError, "Wrong number of bars."
  end

  decoded_string = ''

  wn_pattern.scan(/.{8}/).each do |chunk|

    found = false

    PATTERNS.each do |char,hsh|
      if chunk == hsh['wn']
        decoded_string += char
        found = true
        break;
      end
    end

    raise UndecodableCharactersError, "Invalid sequence: #{chunk}" unless found

  end

  MSI.new(decoded_string, options)
end