Class: Cachd::Proc

Inherits:
Proc
  • Object
show all
Defined in:
lib/cachd/proc.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ttl:, &block) ⇒ Cachd::Proc

Create a new Cachd::Proc

Parameters:

  • ttl (Integer, #to_i)

    The time (in seconds) to cache the result for

  • &block (Proc)

    The proc to run



13
14
15
16
17
# File 'lib/cachd/proc.rb', line 13

def initialize(ttl:, &block)
  @ttl = ttl.to_i
  @cache = {}
  super(&block)
end

Instance Attribute Details

#ttlObject (readonly)

Returns The time (in seconds) to cache the result for

Returns:

  • The time (in seconds) to cache the result for



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/cachd/proc.rb', line 6

class Proc < ::Proc
  attr_reader :ttl

  # Create a new Cachd::Proc
  # @param ttl [Integer, #to_i] The time (in seconds) to cache the result for
  # @param &block [Proc] The proc to run
  # @return [Cachd::Proc]
  def initialize(ttl:, &block)
    @ttl = ttl.to_i
    @cache = {}
    super(&block)
  end

  # Call the proc with the passed attributes, returns whatever the proc does
  def call(*args)
    expires_at, value = @cache[args]
    return value unless expires_at.nil?  or  expires_at <= Time.now
    expires_at = Time.now + @ttl
    value = super(*args)
    @cache[args] = [expires_at, value]
    value
  end

  # Clear the cache completly
  # @return [Integer] The number of items removed
  def clear
    keys = @cache.keys.count
    @cache.delete_if { true }
    keys
  end

  # Clear only expired items from the cache
  # @return [Integer] The number of items removed
  def clear_expired
    keys = @cache.keys.count
    @cache.delete_if { |_k, v| v[0] <= Time.now }
    keys - @cache.keys.count
  end

end

Instance Method Details

#call(*args) ⇒ Object

Call the proc with the passed attributes, returns whatever the proc does



20
21
22
23
24
25
26
27
# File 'lib/cachd/proc.rb', line 20

def call(*args)
  expires_at, value = @cache[args]
  return value unless expires_at.nil?  or  expires_at <= Time.now
  expires_at = Time.now + @ttl
  value = super(*args)
  @cache[args] = [expires_at, value]
  value
end

#clearInteger

Clear the cache completly

Returns:

  • (Integer)

    The number of items removed



31
32
33
34
35
# File 'lib/cachd/proc.rb', line 31

def clear
  keys = @cache.keys.count
  @cache.delete_if { true }
  keys
end

#clear_expiredInteger

Clear only expired items from the cache

Returns:

  • (Integer)

    The number of items removed



39
40
41
42
43
# File 'lib/cachd/proc.rb', line 39

def clear_expired
  keys = @cache.keys.count
  @cache.delete_if { |_k, v| v[0] <= Time.now }
  keys - @cache.keys.count
end