Class: Stockade::Lexer

Inherits:
Object
  • Object
show all
Extended by:
Memoist
Defined in:
lib/stockade.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(datum) ⇒ Lexer

Returns a new instance of Lexer.



13
14
15
# File 'lib/stockade.rb', line 13

def initialize(datum)
  @datum = datum.strip.dup
end

Instance Attribute Details

#datumObject (readonly)

Returns the value of attribute datum.



11
12
13
# File 'lib/stockade.rb', line 11

def datum
  @datum
end

Class Method Details

.call(datum) ⇒ Object



17
18
19
# File 'lib/stockade.rb', line 17

def self.call(datum)
  new(datum).call
end

Instance Method Details

#callObject



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
# File 'lib/stockade.rb', line 36

def call
  res = []

  patterns.each do |name, regex|
    scanner = StringScanner.new(datum)

    loop do
      break unless scanner.scan_until(regex)
      value = scanner.matched

      lexeme = name
      if lexeme == :name
        lexeme = :surname if surname?(value)
        lexeme = :firstname if firstname?(value)
      end
      next if lexeme == :name

      res << {
        lexeme: lexeme,
        value: scanner.matched
      }

      @datum = @datum[0..scanner.pos-scanner.matched.size] +
        '*' * scanner.matched.size +
        @datum[scanner.pos..-1]
    end
  end

  res
end

#name_regexObject



67
68
69
# File 'lib/stockade.rb', line 67

def name_regex
  /\w+/
end

#patternsObject

order is important - from most specific to least the first one that matches stops the scan



23
24
25
26
27
28
29
# File 'lib/stockade.rb', line 23

def patterns
  {
    email: email_regex,
    phone: phone_regex,
    name: name_regex,
  }
end

#scannerObject



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

def scanner
  StringScanner.new(datum)
end

#word_regexObject



71
72
73
# File 'lib/stockade.rb', line 71

def word_regex
  /\W+/
end