Class: Tins::Unit::UnitParser

Inherits:
StringScanner
  • Object
show all
Defined in:
lib/tins/unit.rb

Constant Summary collapse

NUMBER =
/([+-]?
  (?:0|[1-9]\d*)
  (?:
    \.\d+(?i:e[+-]?\d+) |
    \.\d+ |
    (?i:e[+-]?\d+)
  )?
)/x

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, unit, prefixes = nil) ⇒ UnitParser

Returns a new instance of UnitParser.



55
56
57
58
59
60
61
62
63
64
# File 'lib/tins/unit.rb', line 55

def initialize(source, unit, prefixes = nil)
  super source
  if prefixes
    @unit_re = unit_re(Tins::Unit.prefixes(prefixes), unit)
  else
    @unit_lc_re = unit_re(Tins::Unit.prefixes(:lc), unit)
    @unit_uc_re = unit_re(Tins::Unit.prefixes(:uc), unit)
  end
  @number       = 1.0
end

Instance Attribute Details

#numberObject (readonly)

Returns the value of attribute number.



78
79
80
# File 'lib/tins/unit.rb', line 78

def number
  @number
end

Instance Method Details

#parseObject

Raises:

  • (NotImplementedError)


110
111
112
# File 'lib/tins/unit.rb', line 110

def parse
  raise NotImplementedError
end

#scan(re) ⇒ Object



80
81
82
83
# File 'lib/tins/unit.rb', line 80

def scan(re)
  re.nil? and return
  super
end

#scan_char(char) ⇒ Object



106
107
108
# File 'lib/tins/unit.rb', line 106

def scan_char(char)
  scan(/#{char}/) or return
end

#scan_numberObject



85
86
87
88
# File 'lib/tins/unit.rb', line 85

def scan_number
  scan(NUMBER) or return
  @number *= BigDecimal(self[1])
end

#scan_unitObject



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/tins/unit.rb', line 90

def scan_unit
  case
  when unit = scan(@unit_re)
    prefix = @unit_re.prefixes.find { |pre| pre.name == self[1] } or return
    @number *= prefix.multiplier
  when unit = scan(@unit_lc_re)
    prefix = @unit_lc_re.prefixes.find { |pre| pre.name == self[1] } or return
    @number *= prefix.multiplier
  when unit = scan(@unit_uc_re)
    prefix = @unit_uc_re.prefixes.find { |pre| pre.name == self[1] } or return
    @number *= prefix.multiplier
  else
    return
  end
end