Class: Moneta::Adapters::MemcachedNative

Inherits:
Base
  • Object
show all
Defined in:
lib/moneta/adapters/memcached/native.rb

Overview

Memcached backend (using gem memcached)

Instance Method Summary collapse

Methods inherited from Base

#[], #[]=, #close, #decrement, #fetch, #key?

Methods included from Mixins::WithOptions

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ MemcachedNative

Constructor

Parameters:

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

Options Hash (options):

  • :server (String) — default: '127.0.0.1:11211'

    Memcached server

  • :namespace (String)

    Key namespace

  • :expires (String) — default: 604800

    Default expiration time

  • Other (Object)

    options passed to ‘Memcached#new`



15
16
17
18
19
20
21
22
23
# File 'lib/moneta/adapters/memcached/native.rb', line 15

def initialize(options = {})
  server = options.delete(:server) || '127.0.0.1:11211'
  @expires = options.delete(:expires) || 604800
  options.merge!(:prefix_key => options.delete(:namespace)) if options[:namespace]
  # We don't want a limitation on the key charset. Therefore we use the binary protocol.
  # It is also faster.
  options[:binary_protocol] = true unless options.include?(:binary_protocol)
  @cache = ::Memcached.new(server, options)
end

Instance Method Details

#clear(options = {}) ⇒ Object



65
66
67
68
# File 'lib/moneta/adapters/memcached/native.rb', line 65

def clear(options = {})
  @cache.flush
  self
end

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



41
42
43
44
45
46
# File 'lib/moneta/adapters/memcached/native.rb', line 41

def delete(key, options = {})
  value = @cache.get(key, false)
  @cache.delete(key)
  value
rescue ::Memcached::NotFound
end

#increment(key, amount = 1, options = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/moneta/adapters/memcached/native.rb', line 48

def increment(key, amount = 1, options = {})
  result = if amount >= 0
    @cache.increment(key, amount)
  else
    @cache.decrement(key, -amount)
  end
  # HACK: Throw error if applied to invalid value
  if result == 0
    value = @cache.get(key, false) rescue nil
    raise 'Tried to increment non integer value' unless value.to_s == value.to_i.to_s
  end
  result
rescue ::Memcached::NotFound => ex
  store(key, amount.to_s, options)
  amount
end

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



25
26
27
28
29
30
31
32
33
# File 'lib/moneta/adapters/memcached/native.rb', line 25

def load(key, options = {})
  value = @cache.get(key, false)
  if value && options.include?(:expires)
    store(key, value, options)
  else
    value
  end
rescue ::Memcached::NotFound
end

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



35
36
37
38
39
# File 'lib/moneta/adapters/memcached/native.rb', line 35

def store(key, value, options = {})
  # TTL must be Fixnum
  @cache.set(key, value, options[:expires] || @expires, false)
  value
end