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.



11
12
13
# File 'lib/upc.rb', line 11

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

Class Method Details

.complete(eleven) ⇒ Object

Purely for generating new UPC numbers



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

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
  if remainder == 0
    check = 0
  else
    check = 10 - remainder
  end

  eleven + check.to_s
end

.valid?(upc) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
# File 'lib/upc.rb', line 19

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

Instance Method Details

#to_eanObject



47
48
49
50
# File 'lib/upc.rb', line 47

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

#valid?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/upc.rb', line 15

def valid?
  UPC.valid? @number
end