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]?)/
STDNUMPAT_MULTIPLE =

Same as STDNUMPAT but allowing for all numbers in the provided string

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

Instance Method Summary collapse

Instance Method Details

#extract_multiple_numbers(str) ⇒ Array

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

Parameters:

  • str (String)

    The string from which to extract the ISBN/ISSNs

Returns:

  • (Array)

    An array of extracted identifiers



31
32
33
34
# File 'lib/library_stdnums.rb', line 31

def extract_multiple_numbers(str)
  return [] if str == '' || str.nil?
  str.scan(STDNUMPAT_MULTIPLE).flatten.map{ |i| i.gsub(/\-/, '').upcase }
end

#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

Parameters:

  • str (String)

    The string from which to extract an ISBN/ISSN

Returns:

  • (String)

    The extracted identifier



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)

Parameters:

  • rawnum (String)

    The raw string containing (hopefully) an ISSN/ISBN

  • valid_sizes (Integer, Array<Integer>, nil) (defaults to: nil)

    An integer or array of integers of valid sizes

Returns:

  • (String, nil)

    the reduced and verified number, or nil if there's no match at the right size



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/library_stdnums.rb', line 42

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