Class: RelatonIsbn::Isbn

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

Instance Method Summary collapse

Constructor Details

#initialize(isbn) ⇒ Isbn

Create ISBN object.

Parameters:

  • isbn (String)

    ISBN 13 number



8
9
10
# File 'lib/relaton_isbn/isbn.rb', line 8

def initialize(isbn)
  @isbn = isbn&.delete("-")&.sub(/^ISBN[\s:]/i, "")
end

Instance Method Details

#calc_check_digit10Object



32
33
34
35
36
37
38
39
# File 'lib/relaton_isbn/isbn.rb', line 32

def calc_check_digit10
  sum = 0
  @isbn[..-2].chars.each_with_index do |c, i|
    sum += c.to_i * (10 - i)
  end
  chk = (11 - sum % 11) % 11
  chk == 10 ? "X" : chk.to_s
end

#calc_check_digit13Object



41
42
43
44
45
46
47
# File 'lib/relaton_isbn/isbn.rb', line 41

def calc_check_digit13
  sum = 0
  @isbn[..-2].chars.each_with_index do |c, i|
    sum += c.to_i * (i.even? ? 1 : 3)
  end
  ((10 - sum % 10) % 10).to_s
end

#check10?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/relaton_isbn/isbn.rb', line 24

def check10?
  @isbn[9] == calc_check_digit10
end

#check13?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/relaton_isbn/isbn.rb', line 28

def check13?
  @isbn[12] == calc_check_digit13
end

#check?Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
22
# File 'lib/relaton_isbn/isbn.rb', line 16

def check?
  case @isbn
  when /^\d{9}[\dX]$/i then check10?
  when /^\d{13}$/ then check13?
  else false
  end
end

#convert_to13Object



49
50
51
52
53
54
55
56
57
# File 'lib/relaton_isbn/isbn.rb', line 49

def convert_to13
  return unless check?

  return @isbn if @isbn.size == 13

  @isbn = "978#{@isbn}"
  @isbn[12] = calc_check_digit13
  @isbn
end

#parseObject



12
13
14
# File 'lib/relaton_isbn/isbn.rb', line 12

def parse
  convert_to13
end