class Heliodor::DB

Base class for accessing DBs and building queries @attr file [String] @attr tsafe [Bool] When true, uses mutexes for building queries

Attributes

file[RW]
tsafe[RW]

Public Class Methods

new(file, tsafe = false) click to toggle source
# File lib/heliodor/db.rb, line 7
def initialize(file, tsafe = false)
  @tsafe = tsafe
  @mutex = Mutex.new
  @dtable = { 'heliodor_data' => {
    'name'            => 'Heliodor',
    'version'         => Heliodor::VERSION,
    'bson_version'    => Gem.loaded_specs['bson'].version.version,
    'last_write'      => DateTime.now.strftime,
    'ruby_version'    => RUBY_VERSION,
    'ruby_patchlevel' => RUBY_PATCHLEVEL.to_s,
    'ruby_platform'   => RUBY_PLATFORM
  } }
  @file = File.expand_path(file.to_s)

  if File.exist?(@file)
    f = Zlib::GzipReader.open(File.expand_path(@file))
    bb = BSON::ByteBuffer.new(f.read)
    @dat = Hash.from_bson(bb)
    f.close
  else
    f = Zlib::GzipWriter.open(File.expand_path(@file))
    f.write(@dtable.to_bson.to_s)
    @dat = @dtable.clone
    f.close
  end
end

Public Instance Methods

delete(table) click to toggle source

Deletes given table @param table [String] @return [self]

# File lib/heliodor/db.rb, line 50
def delete(table)
  if @tsafe
    @mutex.synchronize do
      @dat.delete(table)
      write(@dat)
    end
  else
    write(@dat)
    @dat.delete(table)
  end
end
inspect() click to toggle source
# File lib/heliodor/db.rb, line 80
def inspect
  %(#<Heliodor::DB:#{object_id.to_s(16)} @file='#{@file}'>)
end
query(table) click to toggle source

Entry point for building queries @param table [String] @return [Heliodor::Query]

# File lib/heliodor/db.rb, line 37
def query(table)
  if @tsafe
    @mutex.synchronize do
      Heliodor::Query.new(self, table, @dat)
    end
  else
    Heliodor::Query.new(self, table, @dat)
  end
end
tables() click to toggle source

Returns array of table names @return [Array<String>] Array of table names

# File lib/heliodor/db.rb, line 64
def tables
  @dat.keys
end
write(dat) click to toggle source

Writes database to file @return [self]

# File lib/heliodor/db.rb, line 70
def write(dat)
  @dat = dat
  File.truncate(@file, 0) if File.exist?(@file)
  Zlib::GzipWriter.open(File.expand_path(@file)) do |f|
    f.write(dat.merge(@dtable).to_bson.to_s)
    f.close
  end
  self
end