Class: CommerceUnits::UnitParser

Inherits:
Object
  • Object
show all
Defined in:
lib/commerce_units/unit_parser.rb

Defined Under Namespace

Classes: UnexpectedToken

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeUnitParser

Returns a new instance of UnitParser.



27
28
29
30
# File 'lib/commerce_units/unit_parser.rb', line 27

def initialize
  @mode = :multiply
  @unit = CommerceUnits::Unit.new
end

Instance Attribute Details

#unitObject

Returns the value of attribute unit.



26
27
28
# File 'lib/commerce_units/unit_parser.rb', line 26

def unit
  @unit
end

Class Method Details

.parse(string) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/commerce_units/unit_parser.rb', line 4

def parse(string)
  _tokens(string).reduce_with_lookahead(new) do |parser, token, lookahead|
    case token
    when "*"
      parser.multiply_token
    when "/"
      parser.divide_token
    when nil
      parser.eof_token
    else
      parser.units_token token
    end
  end.unit
end

Instance Method Details

#divide_tokenObject



37
38
39
40
41
42
# File 'lib/commerce_units/unit_parser.rb', line 37

def divide_token
  if :units == @mode
    @mode = :divide
  end
  self
end

#eof_tokenObject



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/commerce_units/unit_parser.rb', line 43

def eof_token
  case @mode
  when :multiply
    raise UnexpectedToken, "You need to multiply by a term, not just end the file"
  when :divide
    raise UnexpectedToken, "You need to divide by a term, not just end the file"
  else
    @mode = :eof
  end
  self
end

#multiply_tokenObject



31
32
33
34
35
36
# File 'lib/commerce_units/unit_parser.rb', line 31

def multiply_token
  if :units == @mode
    @mode = :multiply
  end
  self
end

#units_token(token) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/commerce_units/unit_parser.rb', line 54

def units_token(token)
  case @mode
  when :multiply
    @unit *= CommerceUnits::Unit.new.tap { |u| u.numerator = [token] }
    @mode = :units
  when :divide
    @unit *= CommerceUnits::Unit.new.tap { |u| u.denominator = [token] }
    @mode = :units
  else
    raise UnexpectedToken, "You didn't tell me to either divide or multiply by your token: #{token}"
  end
  self
end