Class: Karafka::Web::Tracking::TtlArray

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Core::Helpers::Time
Defined in:
lib/karafka/web/tracking/ttl_array.rb

Overview

Array that allows us to store data points that expire over time automatically.

Instance Method Summary collapse

Constructor Details

#initialize(ttl) ⇒ TtlArray

Returns a new instance of TtlArray.

Parameters:

  • ttl (Integer)

    milliseconds ttl



12
13
14
15
# File 'lib/karafka/web/tracking/ttl_array.rb', line 12

def initialize(ttl)
  @ttl = ttl
  @accu = []
end

Instance Method Details

#<<(value) ⇒ Object

Returns added element.

Parameters:

  • value (Object)

    adds value to the array

Returns:

  • (Object)

    added element



28
29
30
31
32
33
34
# File 'lib/karafka/web/tracking/ttl_array.rb', line 28

def <<(value)
  @accu << { value: value, added_at: monotonic_now }

  clear

  value
end

#eachObject

Iterates over only active elements



18
19
20
21
22
23
24
# File 'lib/karafka/web/tracking/ttl_array.rb', line 18

def each
  clear

  @accu.each do |sample|
    yield sample[:value]
  end
end

#empty?Boolean

Returns is the array empty.

Returns:

  • (Boolean)

    is the array empty



37
38
39
40
# File 'lib/karafka/web/tracking/ttl_array.rb', line 37

def empty?
  clear
  @accu.empty?
end

#to_aArray

Returns pure array version with only active elements.

Returns:

  • (Array)

    pure array version with only active elements



43
44
45
46
# File 'lib/karafka/web/tracking/ttl_array.rb', line 43

def to_a
  clear
  super
end