Method: Fech::Mappings.key_by_regex

Defined in:
lib/fech/mappings.rb

.key_by_regex(hash, label) ⇒ Object

Given a Hash whose keys are string representations of regular expressions, return the value whose key best matches the given label.

Parameters:

  • hash (Hash)

    a Hash with string regular expressions for keys

  • label (String, Symbol, Regexp)

    return the key that best matches this



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/fech/mappings.rb', line 52

def self.key_by_regex(hash, label)
  label = label.source if label.is_a?(Regexp)
  
  # Try matching longer keys first, to ensure more accurate keys are
  # prioritized over less accurate ones.
  hash.keys.sort { |x, y| x.length <=> y.length }.reverse.each do |key|
    return hash[key] if Regexp.new(key, Regexp::IGNORECASE).match(label.to_s)
  end
  
  raise "Attempted to access mapping that has not been generated (#{label}). " +
        "Supported keys match the format: #{hash.keys.join(', ')}"
end