Class: Tins::Unit::FormatParser

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

Overview

A parser for unit specifications that extends StringScanner

This class is responsible for parsing strings that contain numerical values followed by unit specifications, supporting various prefix types and unit formats for flexible unit parsing.

Instance Method Summary collapse

Constructor Details

#initialize(format, unit_parser) ⇒ Tins::Unit::FormatParser

The initialize method sets up a new UnitParser instance with the given format and unit parser.

parsing units with the provided parameters



240
241
242
243
# File 'lib/tins/unit.rb', line 240

def initialize(format, unit_parser)
  super format
  @unit_parser = unit_parser
end

Instance Method Details

#parseFloat

The parse method parses a format string using a unit parser and returns the parsed number.

This method processes a format template by scanning for specific pattern directives (%f for numbers, %U for units, %% for literal percent signs) and validates that the input string matches the expected format. It handles parsing errors by raising ParserError exceptions with descriptive messages about mismatches.

Raises:

  • (ParserError)

    if the format string or input string doesn’t match the expected pattern

  • (ParserError)

    if a required number or unit is missing at a specific location

  • (ParserError)

    if literal percent signs don’t match expected positions



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/tins/unit.rb', line 277

def parse
  reset
  until eos? || @unit_parser.eos?
    case
    when scan(/%f/)
      @unit_parser.scan_number or
        raise ParserError, "\"%f\" expected at #{location}"
    when scan(/%U/)
      @unit_parser.scan_unit or
        raise ParserError, "\"%U\" expected at #{location}"
    when scan(/%%/)
      @unit_parser.scan_char(?%) or
        raise ParserError, "#{?%.inspect} expected at #{location}"
    else
      char = scan(/./)
      @unit_parser.scan_char(char) or
        raise ParserError, "#{char.inspect} expected at #{location}"
    end
  end
  unless eos? && @unit_parser.eos?
    raise ParserError,
      "format #{string.inspect} and string "\
      "#{@unit_parser.string.inspect} do not match"
  end
  @unit_parser.number
end

#resetObject

The reset method resets the unit parser state.

This method calls the superclass reset implementation and then resets the internal unit parser instance to its initial state.



249
250
251
252
# File 'lib/tins/unit.rb', line 249

def reset
  super
  @unit_parser.reset
end