module StdNum::Helpers

Helper methods common to ISBN/ISSN

Constants

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.

STDNUMPAT_MULTIPLE

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

Public Instance Methods

extractNumber(str) click to toggle source

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 @param [String] str The string from which to extract an ISBN/ISSN @return [String] The extracted identifier

# File lib/library_stdnums.rb, line 18
def extractNumber str
  match = STDNUMPAT.match str
  return nil unless match
  return (match[1].gsub(/\-/, '')).upcase
end
extract_multiple_numbers(str) click to toggle source

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 @param [String] str The string from which to extract the ISBN/ISSNs @return [Array] An array of extracted identifiers

# 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
reduce_to_basics(rawnum, valid_sizes = nil) click to toggle source

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. @param [String] rawnum The raw string containing (hopefully) an ISSN/ISBN @param [Integer, Array<Integer>, nil] valid_sizes An integer or array of integers of valid sizes for this type (e.g., 10 or 13 for ISBN, 8 for ISSN) @return [String,nil] the reduced and verified number, or nil if there's no match at the right size

# 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