class Moneta::Expires

Adds expiration support to the underlying store

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

@api public

Public Class Methods

new(adapter, options = {}) click to toggle source

@param [Moneta store] adapter The underlying store @param [Hash] options @option options [String] :expires Default expiration time

Calls superclass method
# File lib/moneta/expires.rb, line 14
def initialize(adapter, options = {})
  raise 'Store already supports feature :expires' if adapter.supports?(:expires)
  super
  self.default_expires = options[:expires]
end

Public Instance Methods

create(key, value, options = {}) click to toggle source

(see Moneta::Proxy#store)

Calls superclass method
# File lib/moneta/expires.rb, line 51
def create(key, value, options = {})
  return super if options.include?(:raw)
  expires = expires_at(options)
  @adapter.create(key, new_entry(value, expires), Utils.without(options, :expires))
end
delete(key, options = {}) click to toggle source

(see Moneta::Proxy#delete)

Calls superclass method
# File lib/moneta/expires.rb, line 44
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 = {}) click to toggle source

(see Moneta::Proxy#key?)

Calls superclass method
# File lib/moneta/expires.rb, line 21
def key?(key, options = {})
  # Transformer might raise exception
  load_entry(key, options) != nil
rescue Exception
  super(key, Utils.without(options, :expires))
end
load(key, options = {}) click to toggle source

(see Moneta::Proxy#load)

Calls superclass method
# File lib/moneta/expires.rb, line 29
def load(key, options = {})
  return super if options.include?(:raw)
  value, expires = load_entry(key, options)
  value
end
store(key, value, options = {}) click to toggle source

(see Moneta::Proxy#store)

Calls superclass method
# File lib/moneta/expires.rb, line 36
def store(key, value, options = {})
  return super if options.include?(:raw)
  expires = expires_at(options)
  super(key, new_entry(value, expires), Utils.without(options, :expires))
  value
end

Private Instance Methods

load_entry(key, options) click to toggle source
# File lib/moneta/expires.rb, line 59
def load_entry(key, options)
  new_expires = expires_at(options, nil)
  options = Utils.without(options, :expires)
  entry = @adapter.load(key, options)
  if entry != nil
    value, expires = entry
    if expires && Time.now.to_i > expires
      delete(key)
      nil
    elsif new_expires != nil
      @adapter.store(key, new_entry(value, new_expires), options)
      entry
    else
      entry
    end
  end
end
new_entry(value, expires) click to toggle source
# File lib/moneta/expires.rb, line 77
def new_entry(value, expires)
  if expires
    [value, expires.to_i]
  elsif Array === value || value == nil
    [value]
  else
    value
  end
end