Sha256: 2ddc8ee45354e62c44da13182531194db5485e3a5c2de0be5d05baa75b54df3a

Contents?: true

Size: 1.01 KB

Versions: 5

Compression:

Stored size: 1.01 KB

Contents

# frozen_string_literal: true

module SuperSettings
  # Helper class for truncating timestamps to a specific precision. This is used by storage engines
  # to ensure that timestamps are stored and compared with the same precision.
  class TimePrecision
    attr_reader :time

    def initialize(time, precision = :microsecond)
      raise ArgumentError.new("Invalid precision: #{precision}") unless valid_precision?(precision)

      @time = time_with_precision(time.to_f, precision) if time
    end

    def to_f
      @time.to_f
    end

    private

    def valid_precision?(precision)
      [:microsecond, :millisecond].include?(precision)
    end

    def time_with_precision(timestamp, precision)
      usec = (timestamp % 1) * 1_000_000.0
      if precision == :millisecond
        milliseconds = (usec / 1000.0).round(3).floor
        Time.at(timestamp.to_i, milliseconds, :millisecond).utc
      else
        microseconds = usec.round
        Time.at(timestamp.to_i, microseconds, :microsecond).utc
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
super_settings-2.1.0 lib/super_settings/time_precision.rb
super_settings-2.0.3 lib/super_settings/time_precision.rb
super_settings-2.0.2 lib/super_settings/time_precision.rb
super_settings-2.0.1 lib/super_settings/time_precision.rb
super_settings-2.0.0 lib/super_settings/time_precision.rb