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
|