Class: EAN13

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

Defined Under Namespace

Classes: Version

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ EAN13

Returns a new instance of EAN13.



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

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

Class Method Details

.complete(twelve) ⇒ Object

Purely for generating new ean numbers



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ean13.rb', line 31

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

  arr = (0..11).to_a.collect do |i|
    if (i+1) % 2 == 0
      twelve[i,1].to_i * 3
    else
      twelve[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

  twelve + check.to_s
end

.valid?(ean) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
# File 'lib/ean13.rb', line 25

def self.valid?(ean)
  ean = ean.to_s
  ean.length == 13 && ean == EAN13.complete(ean[0,12])
end

Instance Method Details

#bookland?Boolean

Returns:

  • (Boolean)


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

def bookland?
  valid? && (@number[0,3] == "978" || @number[0,3] == "979")
end

#san?Boolean

Returns true if this EAN has an embedded SAN

For more info on SANs, see www.bowker.com/index.php/component/content/article/3

Returns:

  • (Boolean)


58
59
60
61
62
63
64
65
66
67
# File 'lib/ean13.rb', line 58

def san?
  return nil unless valid?

  prefix = @number.to_s[0,6]
  if prefix == "079999" || prefix == "503067"
    true
  else
    false
  end
end

#to_gtinObject



88
89
90
91
# File 'lib/ean13.rb', line 88

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

#to_sanObject

convert this EAN to a SAN. returns nil if the EAN doesn’t contain an embedded SAN.

requires the SAN library to be loaded or available. Will raise an error if it’s not



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/ean13.rb', line 75

def to_san
  unless Kernel.const_defined?("SAN")
    begin
      gem 'san'
      require 'san'
    rescue Exception => e
      raise LoadError, "Could not load require SAN library. Try installing the san rubygem."
    end
  end
  return nil unless san?
  SAN.complete(@number[6,6])
end

#to_upcObject



93
94
95
96
97
# File 'lib/ean13.rb', line 93

def to_upc
  return nil unless self.valid?
  return nil unless @number[0,1] == "0"
  @number[1,12]
end

#valid?Boolean

Returns:

  • (Boolean)


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

def valid?
  EAN13.valid? @number
end