Class: UPC

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

Defined Under Namespace

Classes: Version

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ UPC

Returns a new instance of UPC.



13
14
15
# File 'lib/upc.rb', line 13

def initialize(str)
  @number = str.to_s
end

Class Method Details

.complete(eleven) ⇒ Object

Purely for generating new UPC numbers



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/upc.rb', line 27

def self.complete(eleven)
  eleven = eleven.to_s
  return nil unless eleven.length == 11 && eleven.match(/\d{11}/)

  arr = (0..10).to_a.collect do |i|
    if (i+1).odd?
      eleven[i,1].to_i * 3
    else
      eleven[i,1].to_i
    end
  end
  sum = arr.inject { |sum, n| sum + n }
  remainder = sum % 10
  (remainder == 0) ? check = 0 : check = 10 - remainder

  eleven + check.to_s
end

.valid?(upc) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
# File 'lib/upc.rb', line 21

def self.valid?(upc)
  upc = upc.to_s
  upc.length == 12 && upc == UPC.complete(upc[0, 11])
end

Instance Method Details

#to_eanObject



45
46
47
48
# File 'lib/upc.rb', line 45

def to_ean
  return nil unless valid?
  "0#{@number}"
end

#valid?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/upc.rb', line 17

def valid?
  UPC.valid? @number
end