gdbm:簡単なラッパー

method_missingじゃなくて、処理をはさんでGDBMに委譲できたりするといいのになぁ。

require 'gdbm'

class Db
  def initialize(dbname)
    @dbfile = File.expand_path(dbname)
    @lockfile = "#{File.dirname(@dbfile)}/lock_#{File.basename(@dbfile)}"
  end

  def transaction
    File.open(@lockfile, 'a') {|f|
      f.flock(File::LOCK_EX)
      GDBM.open(@dbfile) {|dbm|
        yield(dbm)
      }
    }
  end

  def method_missing(name, *args, &block)
    if GDBM.method_defined?(name)
      transaction {|dbm|
        dbm.send(name, *args, &block)
      }
    else
      super(name, *args, &block)
    end
  end
end