Module: ISBN13
- Defined in:
- lib/isbn13.rb,
lib/version.rb
Constant Summary collapse
- VERSION =
'1.0'
Class Method Summary collapse
- .format(isbn) ⇒ Object
- .ranges_path ⇒ Object
-
.valid?(isbn) ⇒ Boolean
based on ruby example on en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-13.
Class Method Details
.format(isbn) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/isbn13.rb', line 19 def self.format(isbn) raise ISBNError.new("#{isbn} is not a proper ISBN13 number") unless valid_form?(isbn) load breaks = [3] found = false size = nil @ranges.keys.max.to_s.size.downto(3) do |x| found = @ranges.has_key?(isbn[0, x].to_i) size = x break if found end raise ISBNError.new("group not found") unless found breaks << size - breaks.first data = @ranges[isbn[0, size].to_i] pub_size = nil found = false data[:min].upto(isbn.size - breaks.last) do |x| found = data[:ranges].any? { |range| range.cover?(isbn[size, x].to_i) } pub_size = x break if found end raise ISBNError.new("publisher not found") unless found breaks << pub_size breaks << isbn.size - breaks.reduce(&:+) - 1 breaks << 1 result = [] idx = 0 breaks.each do |x| result << isbn[idx, x] idx += x end result.join('-') end |
.ranges_path ⇒ Object
58 59 60 |
# File 'lib/isbn13.rb', line 58 def self.ranges_path File.join(File.dirname(__FILE__), 'ranges.bin') end |
.valid?(isbn) ⇒ Boolean
based on ruby example on en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-13
8 9 10 11 12 13 14 15 16 17 |
# File 'lib/isbn13.rb', line 8 def self.valid?(isbn) return false if isbn.nil? isbn = isbn.gsub(/-/, '') return false unless valid_form?(isbn) sum = 0 13.times { |i| sum += i.modulo(2)==0 ? isbn[i].to_i : isbn[i].to_i*3 } 0 == sum.modulo(10) end |