Class: EyeOfNewt::Tokenizer

Inherits:
Object
  • Object
show all
Defined in:
lib/eye_of_newt/tokenizer.rb

Constant Summary collapse

NO_MATCH =

should never match anything

/a^/
WHITESPACE =
/\s+/
ANYTHING =
/[^()]+/
WORD =
/\w+(-\w+)*/
NUMBER =
/\d+/
OF =
/of/i
OR =
/or/i
A =
/an?/i
TO_TASTE =
/to taste/i

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string, units: EyeOfNewt.units.all, unit_modifiers: EyeOfNewt.units.unit_modifiers) ⇒ Tokenizer

Returns a new instance of Tokenizer.



18
19
20
21
22
23
24
# File 'lib/eye_of_newt/tokenizer.rb', line 18

def initialize(string, units: EyeOfNewt.units.all, unit_modifiers: EyeOfNewt.units.unit_modifiers)
  @string = string
  @units = units
  @unit_modifiers = unit_modifiers
  @ss = StringScanner.new(string)
  @scan_text = nil
end

Instance Attribute Details

#stringObject (readonly)

Returns the value of attribute string.



16
17
18
# File 'lib/eye_of_newt/tokenizer.rb', line 16

def string
  @string
end

#unit_modifiersObject (readonly)

Returns the value of attribute unit_modifiers.



16
17
18
# File 'lib/eye_of_newt/tokenizer.rb', line 16

def unit_modifiers
  @unit_modifiers
end

#unitsObject (readonly)

Returns the value of attribute units.



16
17
18
# File 'lib/eye_of_newt/tokenizer.rb', line 16

def units
  @units
end

Instance Method Details

#next_tokenObject



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/eye_of_newt/tokenizer.rb', line 26

def next_token
  return if @ss.eos?

  @ss.scan(WHITESPACE)

  case
  when @scan_text && text = @ss.scan(/#{ANYTHING}\b/)
    @scan_text = false
    [:TEXT, text]
  when text = @ss.scan(NUMBER)
    [:NUMBER, text]
  when text = @ss.scan(/#{OF}\b/)
    [:OF, text]
  when text = @ss.scan(/#{A}\b/)
    [:A, text]
  when text = @ss.scan(/#{OR}\b/)
    [:OR, text]
  when text = @ss.scan(/#{TO_TASTE}\b/)
    [:TO_TASTE, text]
  when text = @ss.scan(/#{unit_matcher}\b/)
    [:UNIT, text]
  when text = @ss.scan(/#{unit_modifier}\b/)
    [:UNIT_MODIFIER, text]
  when text = @ss.scan(/#{WORD}\b/)
    [:WORD, text]
  else
    x = @ss.getch
    @scan_text = true if x == ',' || x == '('
    [x, x]
  end
end