Class: CommerceUnits::UnitLexer
- Inherits:
-
Object
- Object
- CommerceUnits::UnitLexer
show all
- Defined in:
- lib/commerce_units/unit_lexer.rb
Defined Under Namespace
Classes: UnexpectedCharacter
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
Returns a new instance of UnitLexer.
22
23
24
25
|
# File 'lib/commerce_units/unit_lexer.rb', line 22
def initialize
@tokens = []
@mode = :new_character
end
|
Instance Attribute Details
#tokens ⇒ Object
Returns the value of attribute tokens.
21
22
23
|
# File 'lib/commerce_units/unit_lexer.rb', line 21
def tokens
@tokens
end
|
Class Method Details
.tokenize(string) ⇒ Object
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# File 'lib/commerce_units/unit_lexer.rb', line 4
def tokenize(string)
string.split("").inject(new) do |lexer, character|
case character
when "*"
lexer.multiply_token
when "/"
lexer.divide_token
when " "
lexer.white_space
when /[a-zA-Z0-9]/
lexer.character character
else
raise UnexpectedCharacter, character
end
end.tokens
end
|
Instance Method Details
#character(character) ⇒ Object
39
40
41
42
43
44
45
46
47
48
49
50
51
|
# File 'lib/commerce_units/unit_lexer.rb', line 39
def character(character)
case @mode
when :new_character
@tokens << character
@mode = :character
when :character, :space
@tokens[-1] += character
@mode = :character
else
raise UnexpectedCharacter, "character #{character} doesn't belong here"
end
self
end
|
#divide_token ⇒ Object
29
30
31
|
# File 'lib/commerce_units/unit_lexer.rb', line 29
def divide_token
_operator_token "/"
end
|
#multiply_token ⇒ Object
26
27
28
|
# File 'lib/commerce_units/unit_lexer.rb', line 26
def multiply_token
_operator_token "*"
end
|
#white_space ⇒ Object
32
33
34
35
36
37
38
|
# File 'lib/commerce_units/unit_lexer.rb', line 32
def white_space
if :character == @mode
@tokens[-1] += " "
@mode = :space
end
self
end
|