Class: TimeParser

Inherits:
Object
  • Object
show all
Defined in:
lib/logporter/protocol/syslog3164.rb

Overview

Ruby’s core/stdlib Time.strptime is embarrasingly slow. Let’s do our own.

Constant Summary collapse

@@re_cache =
{}
@@re_formats =
{
  "%b" => "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",
  "%d" => "[ 1-3]?[0-9]",
  "%H" => "[0-9]{2}",
  "%M" => "[0-9]{2}",
  "%S" => "[0-9]{2}",
}

Class Method Summary collapse

Class Method Details

.strptime(string, format) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/logporter/protocol/syslog3164.rb', line 15

def self.strptime(string, format)
  if @@re_cache.include?(format)
    obj = @@re_cache[format]
  else
    captures = []
    pattern = format.gsub(/%[A-z]/) do |spec|
      if @@re_formats.include?(spec)
        captures << spec
        "(#{@@re_formats[spec]})"
      else
        spec
      end
    end
    re = Regexp.new(pattern)
    obj = @@re_cache[format] = {
      :re => re,
      :captures => captures,
    }
  end

  #m = obj[:re].match(string)
  #return nil if !m

  now = Time.new
  time_array = [now.year, now.month, now.day, 0, 0, 0, 0]
  return nil unless string.scan(obj[:re]) do |*captures|
    #obj[:captures].each_with_index do |spec, i|
      #p spec => m[i + 1]
    captures.each_with_index do |spec, i|
      case spec
        when "%y"; time_array[0] = m[i + 1].to_i
        when "%b"; time_array[1] = m[i + 1]
        when "%d"; time_array[2] = m[i + 1].to_i
        when "%H"; time_array[3] = m[i + 1].to_i
        when "%M"; time_array[4] = m[i + 1].to_i
        when "%S"; time_array[5] = m[i + 1].to_i
      end # case spec
    end # each capture
  end # string.scan

  return Time.local(*time_array)
end