Class: Moneta::Expires

Inherits:
Proxy
  • Object
show all
Defined in:
lib/moneta/expires.rb

Overview

Adds expiration support to the underlying store

#store and #load support the :expires option to set/update the expiration time.

Instance Attribute Summary

Attributes inherited from Proxy

#adapter

Instance Method Summary collapse

Methods inherited from Proxy

#clear, #close, #increment

Methods included from Defaults

#[], #[]=, #close, #decrement, #fetch, #increment

Methods included from OptionSupport

#expires, #prefix, #raw, #with

Constructor Details

#initialize(adapter, options = {}) ⇒ Expires

Returns a new instance of Expires.

Parameters:

  • adapter (Moneta store)

    The underlying store

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :expires (String)

    Default expiration time



12
13
14
15
# File 'lib/moneta/expires.rb', line 12

def initialize(adapter, options = {})
  super
  @expires = options[:expires]
end

Instance Method Details

#delete(key, options = {}) ⇒ Object

Delete the key from the store and return the current value

Parameters:

  • key (Object)
  • options (Hash) (defaults to: {})

Returns:

  • (Object)

    current value



48
49
50
51
52
# File 'lib/moneta/expires.rb', line 48

def delete(key, options = {})
  return super if options.include?(:raw)
  value, expires = super
  value if !expires || Time.now.to_i <= expires
end

#key?(key, options = {}) ⇒ Boolean

Exists the value with key

Parameters:

  • key (Object)
  • options (Hash) (defaults to: {})

Returns:

  • (Boolean)


18
19
20
21
22
23
24
# File 'lib/moneta/expires.rb', line 18

def key?(key, options = {})
  # Transformer might raise exception
  load_entry(key, options) != nil
rescue Exception
  options.include?(:expires) && (options = options.dup; options.delete(:expires))
  super(key, options)
end

#load(key, options = {}) ⇒ Object

Fetch value with key. Return nil if the key doesn’t exist

Parameters:

  • key (Object)
  • options (Hash) (defaults to: {})

Returns:

  • (Object)

    value



27
28
29
30
31
# File 'lib/moneta/expires.rb', line 27

def load(key, options = {})
  return super if options.include?(:raw)
  value, expires = load_entry(key, options)
  value
end

#store(key, value, options = {}) ⇒ Object

Store value with key

Parameters:

  • key (Object)
  • value (Object)
  • options (Hash) (defaults to: {})

Returns:

  • value



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/moneta/expires.rb', line 34

def store(key, value, options = {})
  return super if options.include?(:raw)
  expires = options.include?(:expires) && (options = options.dup; options.delete(:expires))
  if expires ||= @expires
    super(key, [value, Time.now.to_i + expires], options)
  elsif Array === value || value == nil
    super(key, [value], options)
  else
    super(key, value, options)
  end
  value
end