Class: Item::UpcMaker

Inherits:
BaseService show all
Defined in:
app/services/item/upc_maker.rb

Overview

Creates GTIN-12 codes for our products based on our GS1 company prefix
Allows generating UPC-A (https://www.gs1.org/standards/barcodes/ean-upc)
For reference:
WarmlyYours Entity GLN 0881308000004
UPC Prefix 881308
GS1 Prefix 0881308
https://www.gs1.org/standards/barcodes/ean-upc
Some code that could be repurposed here: https://github.com/Ibotta/ruby_upc_tools/blob/master/lib/upc_tools.rb

Instance Attribute Summary

Attributes inherited from BaseService

#options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseService

#initialize, #log_debug, #log_error, #log_info, #log_warning, #logger, #tagged_logger

Constructor Details

This class inherits a constructor from BaseService

Class Method Details

.last_upc_code_without_check_digitObject



28
29
30
# File 'app/services/item/upc_maker.rb', line 28

def self.last_upc_code_without_check_digit
  Item.pick("left(max(upc),11)".sql_safe).to_i
end

Instance Method Details

#process(max_upc: nil) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'app/services/item/upc_maker.rb', line 11

def process(max_upc: nil)
  max_upc = self.class.last_upc_code_without_check_digit + 1
  upc_number_array = max_upc.to_s.chars
  upc_sum = 0
  # Calculate the check digit
  (0..10).each do |i|
    upc_sum += if i.modulo(2) == 0
                 upc_number_array[i].to_i * 3
               else
                 upc_number_array[i].to_i * 1
               end
  end
  upc_float = (upc_sum.to_f * 0.1).ceil * 10
  upc_number_array << (upc_float - upc_sum)
  upc_number_array.map(&:to_s).join
end