Class: UPC
- Inherits:
-
Object
- Object
- UPC
- Defined in:
- lib/upc.rb
Defined Under Namespace
Classes: Version
Class Method Summary collapse
-
.complete(eleven) ⇒ Object
Purely for generating new UPC numbers.
- .valid?(upc) ⇒ Boolean
Instance Method Summary collapse
-
#initialize(str) ⇒ UPC
constructor
A new instance of UPC.
- #to_ean ⇒ Object
- #valid? ⇒ Boolean
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
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_ean ⇒ Object
45 46 47 48 |
# File 'lib/upc.rb', line 45 def to_ean return nil unless valid? "0#{@number}" end |
#valid? ⇒ Boolean
17 18 19 |
# File 'lib/upc.rb', line 17 def valid? UPC.valid? @number end |