Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persistent hashtable for Ruby programs?

Tags:

ruby

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.

like image 499
taw Avatar asked Jul 10 '09 14:07

taw


2 Answers

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
like image 125
gerrit Avatar answered Nov 18 '22 04:11

gerrit


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
like image 4
Ryan McGeary Avatar answered Nov 18 '22 04:11

Ryan McGeary