Module: Petrarca::ISBN13

Extended by:
ISBN13
Included in:
ISBN13
Defined in:
lib/petrarca/isbn13.rb

Instance Method Summary collapse

Instance Method Details

#calc_check_digit(isbn) ⇒ Object



27
28
29
30
31
32
# File 'lib/petrarca/isbn13.rb', line 27

def calc_check_digit(isbn)
  nums = dehyphenate(isbn).split("")[0, 12].map{|x| x.to_i }
  sum = nums.zip([1, 3] * 6).map{|x, y| x * y }.inject(:+)
  check_digit = 10 - (sum % 10)
  check_digit == 10 ? "0" : check_digit.to_s
end

#correct_format?(isbn) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
25
# File 'lib/petrarca/isbn13.rb', line 22

def correct_format?(isbn)
  isbn = dehyphenate(isbn)
  !!(/\A97[89]\d{9}\d\z/ =~ isbn)
end

#dehyphenate(isbn) ⇒ Object



34
35
36
# File 'lib/petrarca/isbn13.rb', line 34

def dehyphenate(isbn)
  Petrarca.dehyphenate(isbn)
end

#hyphenate(isbn) ⇒ Object



38
39
40
# File 'lib/petrarca/isbn13.rb', line 38

def hyphenate(isbn)
  split(isbn).join("-")
end

#split(isbn) ⇒ Object



42
43
44
# File 'lib/petrarca/isbn13.rb', line 42

def split(isbn)
  Helpers.split(isbn)
end

#valid?(isbn) ⇒ Boolean

Returns:

  • (Boolean)


9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/petrarca/isbn13.rb', line 9

def valid?(isbn)
  isbn = isbn.to_s
  if correct_format?(isbn) && isbn[-1] == calc_check_digit(isbn)
    if isbn.include?("-")
      Helpers.split(isbn) == isbn.split("-")
    else
      true
    end
  else
    false
  end
end