Class: Philiprehberger::CacheKit::Entry

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/cache_kit/entry.rb

Overview

Internal cache entry with value, TTL, and tags.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, ttl: nil, tags: []) ⇒ Entry

Returns a new instance of Entry.

Parameters:

  • value

    the cached value

  • ttl (Numeric, nil) (defaults to: nil)

    time-to-live in seconds (nil = no expiry)

  • tags (Array<String>) (defaults to: [])

    tags for bulk invalidation



12
13
14
15
16
17
# File 'lib/philiprehberger/cache_kit/entry.rb', line 12

def initialize(value, ttl: nil, tags: [])
  @value = value
  @ttl = ttl
  @tags = tags.map(&:to_s)
  @created_at = Time.now
end

Instance Attribute Details

#created_atObject (readonly)

Returns the value of attribute created_at.



7
8
9
# File 'lib/philiprehberger/cache_kit/entry.rb', line 7

def created_at
  @created_at
end

#tagsObject (readonly)

Returns the value of attribute tags.



7
8
9
# File 'lib/philiprehberger/cache_kit/entry.rb', line 7

def tags
  @tags
end

#ttlObject (readonly)

Returns the value of attribute ttl.



7
8
9
# File 'lib/philiprehberger/cache_kit/entry.rb', line 7

def ttl
  @ttl
end

#valueObject (readonly)

Returns the value of attribute value.



7
8
9
# File 'lib/philiprehberger/cache_kit/entry.rb', line 7

def value
  @value
end

Instance Method Details

#expire_atTime?

Absolute expiration time, or nil if the entry has no TTL.

Returns:

  • (Time, nil)


31
32
33
34
35
# File 'lib/philiprehberger/cache_kit/entry.rb', line 31

def expire_at
  return nil if @ttl.nil?

  @created_at + @ttl
end

#expired?Boolean

Check if the entry has expired.

Returns:

  • (Boolean)


22
23
24
25
26
# File 'lib/philiprehberger/cache_kit/entry.rb', line 22

def expired?
  return false if @ttl.nil?

  (Time.now - @created_at) >= @ttl
end

#remaining_ttlFloat?

Remaining seconds until expiry. Returns nil if no TTL is set, or 0.0 if the entry has already expired.

Returns:

  • (Float, nil)


41
42
43
44
45
46
# File 'lib/philiprehberger/cache_kit/entry.rb', line 41

def remaining_ttl
  return nil if @ttl.nil?

  remaining = @ttl - (Time.now - @created_at)
  remaining.positive? ? remaining : 0.0
end