Class: Dogtag::Timestamp

Inherits:
Object
  • Object
show all
Defined in:
lib/dogtag/timestamp.rb

Constant Summary collapse

ONE_SECOND_IN_MILLIS =
1_000
ONE_MILLI_IN_MICRO_SECS =
1_000

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(milliseconds, epoch: 0) ⇒ Timestamp

Returns a new instance of Timestamp.



8
9
10
11
# File 'lib/dogtag/timestamp.rb', line 8

def initialize(milliseconds, epoch: 0)
  @milliseconds = milliseconds
  @epoch = epoch
end

Instance Attribute Details

#epochObject (readonly)

Returns the value of attribute epoch.



6
7
8
# File 'lib/dogtag/timestamp.rb', line 6

def epoch
  @epoch
end

#millisecondsObject (readonly) Also known as: to_i

Returns the value of attribute milliseconds.



6
7
8
# File 'lib/dogtag/timestamp.rb', line 6

def milliseconds
  @milliseconds
end

Class Method Details

.from_redis(seconds_part, microseconds_part) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/dogtag/timestamp.rb', line 37

def self.from_redis(seconds_part, microseconds_part)
  # NOTE: we're dropping the microseconds here because we don't need that
  # level of precision
  milliseconds = (
    (seconds_part * ONE_SECOND_IN_MILLIS) +
    (microseconds_part / ONE_MILLI_IN_MICRO_SECS)
  )

  new(milliseconds)
end

Instance Method Details

#microseconds_partObject



17
18
19
# File 'lib/dogtag/timestamp.rb', line 17

def microseconds_part
  (milliseconds - (seconds * ONE_SECOND_IN_MILLIS)) * ONE_MILLI_IN_MICRO_SECS
end

#secondsObject



13
14
15
# File 'lib/dogtag/timestamp.rb', line 13

def seconds
  (milliseconds / ONE_SECOND_IN_MILLIS).floor
end

#to_timeObject



23
24
25
# File 'lib/dogtag/timestamp.rb', line 23

def to_time
  Time.at(with_unix_epoch.seconds, with_unix_epoch.microseconds_part)
end

#with_epoch(new_epoch) ⇒ Object



31
32
33
34
35
# File 'lib/dogtag/timestamp.rb', line 31

def with_epoch(new_epoch)
  new_milliseconds = milliseconds - (new_epoch - epoch)

  self.class.new(new_milliseconds, epoch: new_epoch)
end

#with_unix_epochObject



27
28
29
# File 'lib/dogtag/timestamp.rb', line 27

def with_unix_epoch
  @with_unix_epoch ||= with_epoch(0)
end