Method: Dalli::Client#cas

Defined in:
lib/dalli/client.rb

#cas(key, ttl = nil, options = nil) ⇒ Object

compare and swap values using optimistic locking. Fetch the existing value for key. If it exists, yield the value to the block. Add the block’s return value as the new value for the key. Add will fail if someone else changed the value.

Returns:

  • nil if the key did not exist.

  • false if the value was changed by someone else.

  • true if the value was successfully updated.



95
96
97
98
99
100
101
102
103
# File 'lib/dalli/client.rb', line 95

def cas(key, ttl=nil, options=nil)
  ttl ||= @options[:expires_in].to_i
  (value, cas) = perform(:cas, key)
  value = (!value || value == 'Not found') ? nil : value
  if value
    newvalue = yield(value)
    perform(:set, key, newvalue, ttl, cas, options)
  end
end