Class: KDL::Types::Email::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/kdl/types/email/parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(string, idn: false) ⇒ Parser

Returns a new instance of Parser.



7
8
9
10
11
# File 'lib/kdl/types/email/parser.rb', line 7

def initialize(string, idn: false)
  @string = string
  @idn = idn
  @tokenizer = Tokenizer.new(string, idn: idn)
end

Instance Method Details

#parseObject



13
14
15
16
17
18
19
20
21
22
23
24
25
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
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/kdl/types/email/parser.rb', line 13

def parse
  local = ''
  unicode_domain = nil
  domain = nil
  context = :start

  loop do
    type, value = @tokenizer.next_token

    case type
    when :part
      case context
      when :start, :after_dot
        local += value
        context = :after_part
      else
        raise ArgumentError, "invalid email #{@string} (unexpected part #{value} at #{context})"
      end
    when :dot
      case context
      when :after_part
        local += value
        context = :after_dot
      else
        raise ArgumentError, "invalid email #{@string} (unexpected dot at #{context})"
      end
    when :at
      case context
      when :after_part
        context = :after_at
      end
    when :domain
      case context
      when :after_at
        validator = (@idn ? IDNHostname : Hostname)::Validator.new(value)
        raise ArgumentError, "invalid hostname #{value}" unless validator.valid?

        unicode_domain = validator.unicode
        domain = validator.ascii
        context = :after_domain
      else
        raise ArgumentError, "invalid email #{@string} (unexpected domain at #{context})"
      end
    when :end
      case context
      when :after_domain
        if local.size > 64
          raise ArgumentError, "invalid email #{@string} (local part length #{local.size} exceeds maximaum of 64)"
        end

        return [local, domain, unicode_domain]
      else
        raise ArgumentError, "invalid email #{@string} (unexpected end at #{context})"
      end
    end
  end
end