Back to Blogs

Hello World with Couchbase and Ruby

Raghavan Srinivas Published

Filter blogs by:

For those of you who might have seen my other blog, my goal is to convey the fact that using Couchbase with any of the language client libraries is very straightforward. The client libraries handle the complexity of the connection and the inherent distributed nature of the cluster. Here's the Hello World code in Ruby.

require 'rubygems'
require 'couchbase'
client = ", :quiet=> false"
client.quiet = false
  spoon = client.get "spoon"
  puts spoon
rescue Couchbase::Error::NotFound => e
  puts "There is no spoon."
  client.set "spoon", "Hello World!", :ttl => 10
The idea behind this program is to get the value of a key named spoon and if it does not exist to create one that lives for 10 seconds. The :quiet as false and :ttl as 10 secs. properties allow for raising of an error and for the key to live 10 seconds respectively.
With Ruby and the abundance of Ruby gems, it's possible to easily store and manipulate JSON documents . Here's an example of Beer data in the following form (it's been massaged a little bit) from the openbeerdb.
{"_id":"beer_#42_Cream_Ale","_rev":"1-dbd2b5d711fea235a714146a5cdae6c7","brewery":"Listermann Brewing Company","name":"#42 Cream Ale","category":"Other Style","style":"American-Style Cream Ale or Lager","updated":"2010-07-22 20:00:20"},

A Ruby program to store the data would look something like below. We use the key "_id" in the document to store the details of all the beers on the world in Couchbase. A very simple program that parses the file and stores each entry based on the key.

require 'rubygems'
require 'couchbase'
require 'yajl'
couchbase ='')
beers = Yajl::Parser.parse('beerdb'))
beers.each do |beer|
  couchbase.set(beer['_id'], beer)

I have gone way beyond a simple Hello World. I will be contributing more towards using Ruby Client libraries and Couchbase, but, in the meantime here are some useful links.

Downloading and Installing the Couchbase server

A longer Tutorial example of using Ruby and Couchbase

«   Back to blogs