Class: ZplRender::Barcode::Interleaved2of5

Inherits:
Object
  • Object
show all
Defined in:
lib/zpl_render/barcode/interleaved2of5.rb

Overview

Interleaved 2 of 5 encoder (ZPL ^B2). Digits are encoded in pairs: the first digit as bars, the second as the interleaved spaces.

Defined Under Namespace

Classes: Result

Constant Summary collapse

PATTERNS =
{
  "0" => "nnwwn", "1" => "wnnnw", "2" => "nwnnw", "3" => "wwnnn",
  "4" => "nnwnw", "5" => "wnwnn", "6" => "nwwnn", "7" => "nnnww",
  "8" => "wnnwn", "9" => "nwnwn"
}.freeze

Class Method Summary collapse

Class Method Details

.encode(data, check_digit: false) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/zpl_render/barcode/interleaved2of5.rb', line 16

def self.encode(data, check_digit: false)
  digits = data.to_s.gsub(/\D/, "")
  if check_digit
    sum = 0
    digits.reverse.each_char.with_index { |c, i| sum += c.to_i * (i.even? ? 3 : 1) }
    digits += ((10 - (sum % 10)) % 10).to_s
  end
  digits = "0#{digits}" if digits.length.odd?

  elements = []
  # start: narrow bar, narrow space, narrow bar, narrow space
  2.times { elements << [:narrow, true] << [:narrow, false] }
  digits.chars.each_slice(2) do |a, b|
    bars = PATTERNS.fetch(a)
    spaces = PATTERNS.fetch(b)
    5.times do |i|
      elements << [bars[i] == "w" ? :wide : :narrow, true]
      elements << [spaces[i] == "w" ? :wide : :narrow, false]
    end
  end
  # stop: wide bar, narrow space, narrow bar
  elements << [:wide, true] << [:narrow, false] << [:narrow, true]
  Result.new(elements: elements, interpretation: digits)
end