Class: GS1::CheckDigitCalculator

Inherits:
Object
  • Object
show all
Defined in:
lib/gs1/check_digit_calculator.rb

Overview

GS1 check digit calculation

Implementation of: www.gs1.org/how-calculate-check-digit-manually Notice! This class does not validate the format of the given sequence, only the length.

Constant Summary collapse

MULTIPLIER_ARRAY =
[3, 1] * 9
VALID_LENGTHS =
[7, 11, 12, 13, 17].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sequence) ⇒ CheckDigitCalculator

Returns a new instance of CheckDigitCalculator.

Raises:

  • (ArgumentError)


12
13
14
15
16
17
# File 'lib/gs1/check_digit_calculator.rb', line 12

def initialize(sequence)
  @sequence = sequence
  @reverse_sequence = sequence.chars.reverse

  raise ArgumentError, 'Invalid length' unless VALID_LENGTHS.include?(sequence.size)
end

Class Method Details

.from_sequence(sequence) ⇒ Object



19
20
21
# File 'lib/gs1/check_digit_calculator.rb', line 19

def self.from_sequence(sequence)
  new(sequence).check_digit
end

.with_sequence(sequence) ⇒ Object



23
24
25
# File 'lib/gs1/check_digit_calculator.rb', line 23

def self.with_sequence(sequence)
  new(sequence).calculate_sequence_with_digit
end

Instance Method Details

#calculate_sequence_with_digitObject



31
32
33
# File 'lib/gs1/check_digit_calculator.rb', line 31

def calculate_sequence_with_digit
  sequence + check_digit
end

#check_digitObject



27
28
29
# File 'lib/gs1/check_digit_calculator.rb', line 27

def check_digit
  sub_from_nearest_higher_ten.to_s
end