Class: Timeliness::FormatSet
- Inherits:
-
Object
- Object
- Timeliness::FormatSet
- Defined in:
- lib/timeliness/format_set.rb
Instance Attribute Summary collapse
-
#formats ⇒ Object
readonly
Returns the value of attribute formats.
-
#regexp ⇒ Object
readonly
Returns the value of attribute regexp.
Class Method Summary collapse
Instance Method Summary collapse
-
#compile! ⇒ Object
Compiles the formats into one big regexp.
-
#initialize(formats) ⇒ FormatSet
constructor
A new instance of FormatSet.
- #match(string, format_string = nil) ⇒ Object
- #single_format(format_string) ⇒ Object
Constructor Details
#initialize(formats) ⇒ FormatSet
Returns a new instance of FormatSet.
9 10 11 12 13 |
# File 'lib/timeliness/format_set.rb', line 9 def initialize(formats) @formats = formats @formats_hash = {} @match_indexes = {} end |
Instance Attribute Details
#formats ⇒ Object (readonly)
Returns the value of attribute formats.
3 4 5 |
# File 'lib/timeliness/format_set.rb', line 3 def formats @formats end |
#regexp ⇒ Object (readonly)
Returns the value of attribute regexp.
3 4 5 |
# File 'lib/timeliness/format_set.rb', line 3 def regexp @regexp end |
Class Method Details
.compile(formats) ⇒ Object
5 6 7 |
# File 'lib/timeliness/format_set.rb', line 5 def self.compile(formats) new(formats).compile! end |
Instance Method Details
#compile! ⇒ Object
Compiles the formats into one big regexp. Stores the index of where each format’s capture values begin in the matchdata.
17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/timeliness/format_set.rb', line 17 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 |
#match(string, format_string = nil) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/timeliness/format_set.rb', line 30 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 |