Class: FormatEngine::FormatSpec

Inherits:
Object
  • Object
show all
Defined in:
lib/format_engine/format_spec.rb,
lib/format_engine/format_spec/parse_regex.rb

Overview

The format string parser.

Constant Summary collapse

PARSE_REGEX =

The regular expression used to parse variable specifications.

%r{(?<lead>  (^|(?<=[^\\]))%){0}
 (?<flags> [~@#$^&*=?_<>|!]*){0}
 (?<var> \g<lead>\g<flags>[-+]?(\d+(\.\d+)?)?[a-zA-Z]){0}
 (?<set> \g<lead>\g<flags>(\d+(,\d+)?)?\[([^\]\\]|\\.)+\]){0}
 (?<rgx> \g<lead>\g<flags>\/([^\\ \/]|\\.)*\/([imx]*)){0}
 (?<per> \g<lead>%){0}
 \g<var> | \g<set> | \g<rgx> | \g<per>
}x

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fmt_string) ⇒ FormatSpec

Set up an instance of a format specification.



18
19
20
21
# File 'lib/format_engine/format_spec.rb', line 18

def initialize(fmt_string)
  @specs = []
  scan_spec(fmt_string)
end

Instance Attribute Details

#specsObject (readonly)

The array of specifications that were extracted.



15
16
17
# File 'lib/format_engine/format_spec.rb', line 15

def specs
  @specs
end

Instance Method Details

#scan_spec(fmt_string) ⇒ Object

Scan the format string extracting literals and variables.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/format_engine/format_spec.rb', line 30

def scan_spec(fmt_string)
  until fmt_string.empty?
    if (match_data = PARSE_REGEX.match(fmt_string))
      mid = match_data.to_s
      pre = match_data.pre_match

      @specs << FormatLiteral.new(pre) unless pre.empty?
      @specs << case
                when match_data[:var] then FormatVariable.new(mid)
                when match_data[:set] then FormatSet.new(mid)
                when match_data[:rgx] then FormatRgx.new(mid)
                when match_data[:per] then FormatLiteral.new("\%")
                else fail "Impossible case in scan_spec."
                end
      fmt_string = match_data.post_match
    else
      @specs << FormatLiteral.new(fmt_string)
      fmt_string = ""
    end
  end
end

#validate(engine) ⇒ Object

Validate the specs of this format against the engine.



24
25
26
27
# File 'lib/format_engine/format_spec.rb', line 24

def validate(engine)
  specs.each {|item| item.validate(engine)}
  self
end