Class: Relaton::Isbn::Isbn
- Inherits:
-
Object
- Object
- Relaton::Isbn::Isbn
- Defined in:
- lib/relaton/isbn/isbn.rb
Instance Method Summary collapse
- #calc_check_digit10 ⇒ Object
- #calc_check_digit13 ⇒ Object
- #check10? ⇒ Boolean
- #check13? ⇒ Boolean
- #check? ⇒ Boolean
- #convert_to13 ⇒ Object
-
#initialize(isbn) ⇒ Isbn
constructor
Create ISBN object.
- #parse ⇒ Object
Constructor Details
#initialize(isbn) ⇒ Isbn
Create ISBN object.
9 10 11 |
# File 'lib/relaton/isbn/isbn.rb', line 9 def initialize(isbn) @isbn = isbn&.delete("-")&.sub(/^ISBN[\s:]/i, "") end |
Instance Method Details
#calc_check_digit10 ⇒ Object
33 34 35 36 37 38 39 40 |
# File 'lib/relaton/isbn/isbn.rb', line 33 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_digit13 ⇒ Object
42 43 44 45 46 47 48 |
# File 'lib/relaton/isbn/isbn.rb', line 42 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
25 26 27 |
# File 'lib/relaton/isbn/isbn.rb', line 25 def check10? @isbn[9] == calc_check_digit10 end |
#check13? ⇒ Boolean
29 30 31 |
# File 'lib/relaton/isbn/isbn.rb', line 29 def check13? @isbn[12] == calc_check_digit13 end |
#check? ⇒ Boolean
17 18 19 20 21 22 23 |
# File 'lib/relaton/isbn/isbn.rb', line 17 def check? case @isbn when /^\d{9}[\dX]$/i then check10? when /^\d{13}$/ then check13? else false end end |
#convert_to13 ⇒ Object
50 51 52 53 54 55 56 57 58 |
# File 'lib/relaton/isbn/isbn.rb', line 50 def convert_to13 return unless check? return @isbn if @isbn.size == 13 @isbn = "978#{@isbn}" @isbn[12] = calc_check_digit13 @isbn end |
#parse ⇒ Object
13 14 15 |
# File 'lib/relaton/isbn/isbn.rb', line 13 def parse convert_to13 end |