Sha256: ec7b90a747530c79857c02828046c67cd2dcd496e26885b1379ce0180b6ef749

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

module Timeliness
  class FormatSet
    attr_reader :formats, :regexp

    def self.compile(formats)
      new(formats).compile!
    end

    def initialize(formats)
      @formats       = formats
      @formats_hash  = {}
      @match_indexes = {}
    end

    # Compiles the formats into one big regexp. Stores the index of where
    # each format's capture values begin in the matchdata.
    def compile!
      regexp_string = ''
      @formats.inject(0) { |index, format_string|
        format = Format.new(format_string).compile!
        @formats_hash[format_string] = format
        @match_indexes[index] = format
        regexp_string.concat("(?>#{format.regexp_string})|")
        index + format.token_count
      }
      @regexp = %r[\A(?:#{regexp_string.chop})\z]
      self
    end

    def match(string, format_string=nil)
      format = single_format(format_string) if format_string
      match_regexp = format && format.regexp || @regexp

      match_regexp.match(string) do |match_data|
        captures = match_data.captures                  # For a multi-format regexp there are lots of nils
        index    = captures.find_index { |e| !e.nil? }  # Find the start of captures for matched format
        values   = captures.values_at(index..(index+7))
        format ||= @match_indexes[index]
        format.process(*values)
      end
    end

    def single_format(format_string)
      @formats_hash.fetch(format_string) { Format.new(format_string).compile! }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
timeliness-0.5.0 lib/timeliness/format_set.rb