Module: Petrarca::ISBN10

Extended by:
ISBN10
Included in:
ISBN10
Defined in:
lib/petrarca/isbn10.rb

Instance Method Summary collapse

Instance Method Details

#calc_check_digit(isbn) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/petrarca/isbn10.rb', line 27

def calc_check_digit(isbn)
  nums = isbn.to_s.delete("-").split("")[0, 9].map{|x| x.to_i }
  sum = nums.zip((2..10).to_a.reverse).map{|x, y| x * y }.inject(:+)
  check_digit = 11 - (sum % 11)
  case check_digit
  when 10
    "X"
  when 11
    "0"
  else
    check_digit.to_s
  end
end

#correct_format?(isbn) ⇒ Boolean

Returns:

  • (Boolean)


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

def correct_format?(isbn)
  isbn = isbn.to_s.delete("-")
  !!(/\A\d{9}[0-9X]\z/ =~ isbn)
end

#hyphenate(isbn) ⇒ Object



41
42
43
# File 'lib/petrarca/isbn10.rb', line 41

def hyphenate(isbn)
  Helpers.split("978" + isbn.to_s).drop(1).join("-")
end

#valid?(isbn) ⇒ Boolean

Returns:

  • (Boolean)


9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/petrarca/isbn10.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("978" + isbn).drop(1) == isbn.split("-")
    else
      true
    end
  else
    false
  end
end