Class: Bookland::ASIN

Inherits:
Identifier show all
Defined in:
lib/bookland/asin.rb

Constant Summary collapse

WEIGHTS =
10.downto(2).to_a.freeze

Instance Attribute Summary

Attributes inherited from Identifier

#digits

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Identifier

#==, #checksum_digit, #data_digits, #initialize, #to_s, valid?

Constructor Details

This class inherits a constructor from Bookland::Identifier

Class Method Details

.calculate_checksum_digit(digits) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/bookland/asin.rb', line 5

def self.calculate_checksum_digit(digits)
  sum = digits.map(&:to_i).zip(WEIGHTS).reduce(0) { |a , (i, j)| a + i * j }

  case checksum_digit = 11 - sum % 11
  when 0..9 then checksum_digit.to_s
  when 10 then 'X'
  when 11 then '0'
  end
end

.from_isbn(isbn) ⇒ Object



15
16
17
18
19
20
# File 'lib/bookland/asin.rb', line 15

def self.from_isbn(isbn)
  data_digits = isbn.split('')[3..11]
  checksum_digit = ASIN.calculate_checksum_digit(data_digits)

  (data_digits << checksum_digit).join
end

.to_isbn(asin) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/bookland/asin.rb', line 22

def self.to_isbn(asin)
  return if asin[0] == 'B'

  data_digits = %w(9 7 8) + asin.split('')[0, 9]
  checksum_digit = ISBN.calculate_checksum_digit(data_digits)

  (data_digits << checksum_digit).join
end

Instance Method Details

#valid?Boolean

Returns:

  • (Boolean)


31
32
33
34
35
36
37
38
# File 'lib/bookland/asin.rb', line 31

def valid?
  case digits.first
  when 'B'
    digits.size == 10
  else
    digits.size == 10 && super
  end
end