Let's first consider the simplest Ruby program to interact with Couchbase. We want to set a key and on subsequent runs of the application we will output the key if it exists or create it if it does not. We'll also set a timeout so that the key we set will expire after 10 seconds.
If you want a head start you can grab the example code and get going straight away. Open up a new Terminal window and type the following:
git clone firstname.lastname@example.org:davidjrice/couchbase-examples-ruby.git cd couchbase-examples-ruby bundle install
Now that you have a copy of the code, let's look at what's happening.
source "http://rubygems.org" gem "active_support" gem "couchbase-ruby-client"
Here we are simply requiring all Gem dependencies for the
hello-world.rb example. If you didn't have
them already they will be installed when you run bundle
require 'rubygems' require 'bundler/setup' Bundler.require(:default) client = Couchbase.new "http://
localhost:8091/pools/default" begin spoon = client.get "spoon" puts spoon rescue Memcached::NotFound => e puts "There is no spoon." client.set "spoon", "Hello World!", 10 end
The first 3 lines are some bootstrap code for
Bundler, to load it and then have it load all
the Gems specified in our
We then create a new connection to our Couchbase Server. Remember
to change the connection details
localhost:8091 if you are working with
couchbase remotely or on another port.
The last 7 lines are the meat of what's happening, let's go through them in more detail:
begin ... rescue Memcached::NotFound => e ... end
If we try to retrieve a key from Couchbase that does not exist it will raise a Memcached::NotFound error. So to be able to handle this we start a begin/rescue block and specify we want to only rescue from that error.
spoon = client.get "spoon" puts spoon
Now we attempt to get the contents of the key "spoon". If it exists, we continue and output the value of that key.
puts "There is no spoon." client.set "spoon", "Hello World!", 10
Lastly if the key doesn't exist and our attempt to get raises a Memcached::NotFound error then our rescue block will be triggered. In which we're just outputting to the terminal again and then setting a value for our key "spoon". For the purposes of the example we're passing a 3rd (optional) paramter to the set method specifying a TTL Time to Live (expiry time in seconds).
That's it. We're ready to run our first Couchbase program.
The first time you run the program it should produce the following output
➜ couchbase-examples-ruby ruby hello-world.rb There is no spoon.
If you are to run it again within 10 seconds it should produce this output
➜ couchbase-examples-ruby ruby hello-world.rb Hello World!
Way to go! You've just interacted with Couchbase for the first time. We've looked at getting and setting the value of a key and expiring the cache.