The most commonly recommended Ruby wrapper for LevelDB is from https://github.com/wmorgan/leveldb-ruby and can be installed, as seen in the log file included in the code samples for this chapter, with a gem command:
sudo gem install leveldb-ruby
Note that it has been stalled since 2011 and is minimal, not even including batch support. However, it supports the basics with code similar to the previous Python code:
require 'leveldb' # open a data store db = LevelDB::DB.new("/tmp/testleveldb11_ruby.db") # a simple Put operation db.put('name', 'William Bloggs') db.put('spouse', 'Josephine Bloggs') db.put('dog', 'Kilroy') db.put('occupation', 'Dev') db.close()
Unlike the Python code, reading back is idiomatically Ruby code where you can just treat the database as a dictionary and apply a block to it:
db.each do |k,v| puts "Key=#{k}, Value=#{v}" end
A much more useful and complete wrapper is https://github.com/DAddYE/leveldb which includes nicer iterators and batches but has a more complex install and needs Ruby 2.0. It adds batch support:
db.batch do |b| b.put 'spouse', 'Josephine Bloggs' b.put 'dog', 'Kilroy' b.delete 'name' end
This sample as a Ruby style of code blocks uses the idiom that the block contains all the logic to apply to the batch so implies a write at the end of the block.