Search:

Search all manuals
Search this manual
Manual
Couchbase Client Library Ruby 1.1
Community Wiki and Resources
Download Client Library
RDoc
Ruby Client Library
SDK Forum
Additional Resources
Community Wiki
Community Forums
Couchbase SDKs
Parent Section
7 Ruby — Update Operations
Chapter Sections
Chapters

7.2. Compare and Swap

Takes a given key, gets the value for the key, and yields it to a block. Replaces the value in the datastore with the result of the block as long as the key has not been updated in the meantime. If the the key has been successfully updated in the datastore, a new CAS value will be returned raises Error::KeyExists.

CAS stands for "compare and swap", and avoids the need for manual key mutexing.

API Callobject.cas(key [, ruby-cas-options ])
Asynchronousyes
Description Compare and set a value providing the supplied CAS key matches
Returns ( Check and set object )
Arguments 
string key Document ID used to identify the value
hash ruby-cas-options Hash of options containing key/value pairs
 Structure definition:
 :ttl (int) :ttl (Expiration)  
  Time for document to exist in server before it is automatically destroyed. This option symbol is :ttl and the value can be any number representing seconds.
 :format (symbol) How to represent value in storage.  
  Determines how a value is represented in storage. Possible values include :document for JSON data, :plain for string storage, and :marshal to serialize your ruby object using Marshall.dump and Marshal.load.
 :flags (fixnum) Flags for storage options.  
  Flags used during the commit. These flags are ignored by the Couchbase server but preserved for use by a client. This includes default flags recorded for new values and was used as part of the memcached protocol.
Exceptions 
Couchbase::Error::KeyExists Exception object indicateing the key was updated before the codeblock has completed and therefore the CAS value had changed.

The following illustrates use of the cas function:

#appends to a JSON-encoded value
# first sets value and formatting for stored value
        c.default_format = :document
        c.set("foo", {"bar" => 1})

#perform cas and provide value to block
        c.cas("foo") do |val|
              val["baz"] = 2
              val
        end

# returns {"bar" => 1, "baz" => 2}
        c.get("foo")