Module: Petrarca::Helpers

Extended by:
Helpers
Included in:
Helpers
Defined in:
lib/petrarca/helpers.rb

Instance Method Summary collapse

Instance Method Details

#load_ranges(range_file) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/petrarca/helpers.rb', line 51

def load_ranges(range_file)
  ranges = {}
  File.open(range_file, "r") do |f|
    f.each_line do |line|
      next if line.start_with?("#")
      g, r = line.chomp.split(":")
      ranges[g] = r.split(",") unless r.nil?
    end
  end
  ranges
end

#split(isbn) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/petrarca/helpers.rb', line 10

def split(isbn)
  isbn = Petrarca.dehyphenate(isbn)
  ean_prefix = isbn[0, 3]
  unless ean_prefix == "978" || ean_prefix == "979"
    raise InvalidEANPrefixError.new("Invalid EAN prefix: #{ean_prefix}")
  end
  body = isbn[3, 9]
  check_digit = isbn[12, 1]
  begin
    registration_group, body = Helpers.split_to_parts(body, REGISTRATION_GROUP_RANGES[ean_prefix])
  rescue InvalidRangeError
    raise InvalidRangeError.new("Registration group is not defined: #{body} (under #{ean_prefix})")
  end
  prefix = "#{ean_prefix}-#{registration_group}"
  begin
    registrant, publication = Helpers.split_to_parts(body, REGISTRANT_RANGES[prefix])
  rescue InvalidRangeError
    raise InvalidRangeError.new("Registrant is not defined: #{body} (under #{prefix})")
  end
  [ean_prefix, registration_group, registrant, publication, check_digit]
end

#split_to_parts(body, ranges) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/petrarca/helpers.rb', line 33

def split_to_parts(body, ranges)
  parts = ranges.map do |range_str|
    s, e = range_str.split("-")
    prefix = body[0, s.size]
    if Range.new(s.to_i, e.to_i).cover?(prefix.to_i)
      [prefix, body[(prefix.size)..]]
    else
      nil
    end
  end.compact
  unless parts.empty?
    parts.first
  else
    raise InvalidRangeError.new(body)
  end
end