Class: OpenShip::Sscc

Inherits:
Object
  • Object
show all
Defined in:
lib/open-ship/sscc.rb

Class Method Summary collapse

Class Method Details

.company_prefixObject



8
9
10
# File 'lib/open-ship/sscc.rb', line 8

def self.company_prefix
  @company_prefix
end

.company_prefix=(prefix) ⇒ Object



12
13
14
# File 'lib/open-ship/sscc.rb', line 12

def self.company_prefix=(prefix)
  @company_prefix=prefix
end

.extension_digitObject



16
17
18
# File 'lib/open-ship/sscc.rb', line 16

def self.extension_digit
  @extension_digit
end

.extension_digit=(digit) ⇒ Object



20
21
22
# File 'lib/open-ship/sscc.rb', line 20

def self.extension_digit=(digit)
  @extension_digit = digit
end

.generate_check_digit(string_sequence) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/open-ship/sscc.rb', line 24

def self.generate_check_digit(string_sequence)
  # It's gotta be a string because of the leading zero possibility
  # in the extension digit.
  unless string_sequence.class <= String
    raise "Can only check string sequences."
  end
  unless string_sequence.length == 17
    raise "Sequence must be 17 characters long"
  end
  sequence = []
  string_sequence.each_char { |chr|
    sequence << chr.to_i
  }

  # See http://www.gs1us.org/solutions_services/tools/check_digit_calculator
  array1 = [sequence[0], sequence[2], sequence[4], sequence[6],
    sequence[8], sequence[10], sequence[12], sequence[14], sequence[16]]
  number1 = (array1.inject(:+) * 3)
  array2 = [sequence[1], sequence[3], sequence[5], sequence[7], sequence[9],
    sequence[11], sequence[13], sequence[15]]
  number2 = array2.inject(:+)
  number3 = number1 + number2
  check_digit = (10 - (number3 % 10))
  if check_digit == 10
    check_digit = 0
  end
  check_digit.to_s
end

.generate_sscc_id(serial_reference, opts = {}) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/open-ship/sscc.rb', line 53

def self.generate_sscc_id(serial_reference, opts = {})
  include_prefix = opts[:include_prefix]||false
  if company_prefix.nil?
    raise "Company prefix cannot be nil. Set with OpenShip::Sscc.company_prefix"
  end
  while ((@company_prefix.length + serial_reference.length) < 16)
    serial_reference = "0" + serial_reference
  end
  sequence = @extension_digit + @company_prefix + serial_reference
  check_digit = self.generate_check_digit(sequence)
  if !include_prefix
    sscc = sequence + check_digit
  else
    sscc = ("00" + sequence + check_digit)
  end
  sscc
end