Module: Philiprehberger::EmailValidator::TypoSuggester

Defined in:
lib/philiprehberger/email_validator/typo_suggester.rb

Overview

Typo detection and domain correction suggestions.

Compares the domain part of an email against a list of common providers and suggests corrections when a close match is found.

Constant Summary collapse

COMMON_DOMAINS =

Common email provider domains to check against.

%w[
  gmail.com
  yahoo.com
  hotmail.com
  outlook.com
  icloud.com
  protonmail.com
  aol.com
].freeze

Class Method Summary collapse

Class Method Details

.suggest(email) ⇒ Hash?

Suggest a corrected email if the domain appears to be a typo.

Parameters:

  • email (String)

    the email address to check

Returns:

  • (Hash, nil)

    { original:, suggested: } or nil if no suggestion



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/philiprehberger/email_validator/typo_suggester.rb', line 26

def suggest(email)
  return nil unless email.is_a?(String)

  parts = email.strip.split('@', 2)
  return nil unless parts.length == 2

  local, domain = parts
  return nil if local.empty? || domain.nil? || domain.empty?

  domain_lower = domain.downcase

  # No suggestion needed if domain is already a known provider
  return nil if COMMON_DOMAINS.include?(domain_lower)

  best_match = nil
  best_distance = nil

  COMMON_DOMAINS.each do |known|
    dist = levenshtein(domain_lower, known)
    next unless dist.between?(1, 2)

    if best_distance.nil? || dist < best_distance
      best_distance = dist
      best_match = known
    end
  end

  return nil if best_match.nil?

  { original: email, suggested: "#{local}@#{best_match}" }
end