tags:

views:

434

answers:

5

I need a small unstructured database for my Ruby scripts. Not Sqlite, something more like a persistent hashtables would work perfectly, as long as it can store basic Ruby structures (arrays, strings, hashes etc. - all serializable) and won't get corrupted when Ruby scripts crash.

I know there's plenty of solutions like that for Perl with Tie::Hash, so there's probably some gem like that for Ruby. What gem would that be?

EDIT: As far as I can tell PStore and yaml solutions are based on reading, unmarshaling, remarshaling and writing entire database on every change. That not only requires all of it to fit memory, it's O(n^2). So neither of them seem like a particularly good solution.

+1  A: 

You could use bdb, Ruby interface to the "Berkeley DB" (download link from this URL seems not to work but github does;-).

Alex Martelli
+2  A: 

Perhaps FSDB (file system data base) will suit your needs.

FSDB is a file system data base. FSDB provides a thread-safe, process-safe Database class which uses the native file system as its back end and allows multiple file formats and serialization methods. Users access objects in terms of their paths relative to the base directory of the database. It’s very light weight (the state of a Database is essentially just a path string, and code size is very small, under 1K lines, all ruby).

$ sudo gem install fsdb

Here's an example from the documentation:

require 'fsdb'

db = FSDB::Database.new('/tmp/my-data')

db['recent-movies/myself'] = ["LOTR II", "Austin Powers"]
puts db['recent-movies/myself'][0]              # ==> "LOTR II"

db.edit 'recent-movies/myself' do |list|
  list << "A la recherche du temps perdu"
end
Ryan McGeary
+2  A: 

If the data is small enough to keep in memory while the program is running, and serialize/deserialize when on exit/startup, you could try YAML. It comes default with Ruby and can store any kind of object.

require 'yaml'
hash = { :foo => 'bar', :meh => 42 }
yaml_data = hash.to_yaml
puts yaml_data

Will give you

--- 
:meh: 42
:foo: bar

to load, simply do:

hash = YAML.load(yaml_data)
wvdschel
+1  A: 

There is PStore in the Ruby Standard Library, no need to install anything.

require 'pstore'
store = PStore.new('store.pstore')
store.transaction do
  store['key'] = 'value'
end
gerrit
+1  A: 

Have you tried gdbm? It comes with Ruby stdlib, is really simple and much faster than PStore or YAML.

Pablo Lorenzzoni