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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseService

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

Constructor Details

This class inherits a constructor from BaseService

Class Method Details

.last_upc_code_without_check_digitObject



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

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



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

def process(max_upc:nil)
  max_upc = self.class.last_upc_code_without_check_digit + 1
  upc_number_array = max_upc.to_s.split('')
  upc_sum = 0
  # Calculate the check digit
  (0..10).each do |i|
    if i.modulo(2) == 0
      upc_sum += upc_number_array[i].to_i*3
    else
      upc_sum += 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)
  new_upc = upc_number_array.map{|n| "#{n}"}.join("")
end