Module: StdNum::Helpers

Included in:
ISBN, ISSN
Defined in:
lib/library_stdnums.rb

Overview

Helper methods common to ISBN/ISSN

Constant Summary

STDNUMPAT =

The pattern we use to try and find an ISBN/ISSN. Ditch everthing before the first digit, then take all the digits/hyphens, optionally followed by an 'X' Since the shortest possible string is 7 digits followed by a checksum digit for an ISSN, we'll make sure they're at least that long. Still imperfect (would fine "5------", for example) but should work in most cases.

/^.*?(\d[\d\-]{6,}[xX]?)/

Instance Method Summary collapse

Instance Method Details

#extractNumber(str) ⇒ String

Extract the most likely looking number from the string. This will be the first string of digits-and-hyphens-and-maybe-a-trailing-X, with the hypens removed



18
19
20
21
22
# File 'lib/library_stdnums.rb', line 18

def extractNumber str
  match = STDNUMPAT.match str
  return nil unless match
  return (match[1].gsub(/\-/, '')).upcase
end

#reduce_to_basics(rawnum, valid_sizes = nil) ⇒ String?

Given any string, extract what looks like the most likely ISBN/ISSN of the given size(s), or nil if nothing matches at the correct size. for this type (e.g., 10 or 13 for ISBN, 8 for ISSN)



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

def reduce_to_basics rawnum, valid_sizes = nil
  return nil if rawnum.nil?

  num = extractNumber rawnum

  # Does it even look like a number?
  return nil unless num

  # Return what we've got if we don't care about the size
  return num unless valid_sizes

  # Check for valid size(s)
  [valid_sizes].flatten.each do |s|
    return num if num.size == s
  end

  # Didn't check out size-wise. Return nil
  return nil
end