class Fluent::TimeParser

Public Class Methods

new(format = nil, localtime = true, timezone = nil) click to toggle source
# File lib/fluent/time.rb, line 180
def initialize(format = nil, localtime = true, timezone = nil)
  if format.nil? && (timezone || !localtime)
    raise Fluent::ConfigError, "specifying timezone requires time format"
  end

  @cache1_key = nil
  @cache1_time = nil
  @cache2_key = nil
  @cache2_time = nil

  format_with_timezone = format && (format.include?("%z") || format.include?("%Z"))

  # unixtime_in_expected_tz = unixtime_in_localtime + offset_diff
  offset_diff = case
                when format_with_timezone then nil
                when timezone  then Time.now.localtime.utc_offset - Time.zone_offset(timezone)
                when localtime then 0
                else Time.now.localtime.utc_offset # utc
                end

  strptime = format && (Strptime.new(time_format) rescue nil)

  @parse = case
           when format_with_timezone && strptime then ->(v){ Fluent::EventTime.from_time(strptime.exec(v)) }
           when format_with_timezone             then ->(v){ Fluent::EventTime.from_time(Time.strptime(v, format)) }
           when strptime then ->(v){ t = strptime.exec(v);         Fluent::EventTime.new(t.to_i + offset_diff, t.nsec) }
           when format   then ->(v){ t = Time.strptime(v, format); Fluent::EventTime.new(t.to_i + offset_diff, t.nsec) }
           else ->(v){ Fluent::EventTime.parse(v) }
           end
end

Public Instance Methods

call(value)
Alias for: parse
parse(value) click to toggle source

TODO: new cache mechanism using format string

# File lib/fluent/time.rb, line 212
def parse(value)
  unless value.is_a?(String)
    raise TimeParseError, "value must be string: #{value}"
  end

  if @cache1_key == value
    return @cache1_time
  elsif @cache2_key == value
    return @cache2_time
  else
    begin
      time = @parse.call(value)
    rescue => e
      raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}"
    end
    @cache1_key = @cache2_key
    @cache1_time = @cache2_time
    @cache2_key = value
    @cache2_time = time
    return time
  end
end
Also aliased as: call