Class: Heliodor::DB

Inherits:
Object
  • Object
show all
Defined in:
lib/heliodor/db.rb

Overview

Base class for accessing DBs and building queries

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, tsafe = false) ⇒ DB


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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)
    raw = File.read(File.expand_path(@file))
    bb = BSON::ByteBuffer.new(raw)
    @dat = Hash.from_bson(bb)
  else
    File.open(@file, 'w') do |f|
      f.write(@dtable.to_bson.to_s)
      @dat = @dtable.clone
    end
  end
end

Instance Attribute Details

#fileString


4
5
6
# File 'lib/heliodor/db.rb', line 4

def file
  @file
end

#tsafeBool

When true, uses mutexes for building queries


4
5
6
# File 'lib/heliodor/db.rb', line 4

def tsafe
  @tsafe
end

Instance Method Details

#inspectObject


63
64
65
# File 'lib/heliodor/db.rb', line 63

def inspect
  %(#<Heliodor::DB:#{object_id.to_s(16)} @file='#{@file}'>)
end

#query(table) ⇒ Heliodor::Query

Entry point for building queries


36
37
38
39
40
41
42
43
44
# File 'lib/heliodor/db.rb', line 36

def query(table)
  if @tsafe
    @mutex.synchronize do
      Heliodor::Query.new(self, table, @dat)
    end
  else
    Heliodor::Query.new(self, table, @dat)
  end
end

#tablesArray<String>

Returns array of table names


48
49
50
# File 'lib/heliodor/db.rb', line 48

def tables
  Hash.from_bson(BSON::ByteBuffer.new(File.read(@file))).keys
end

#write(dat) ⇒ self

Writes database to file


54
55
56
57
58
59
60
61
# File 'lib/heliodor/db.rb', line 54

def write(dat)
  @dat = dat
  File.truncate(@file, 0) if File.exist?(@file)
  File.open(@file, 'w') do |f|
    f.write(dat.merge(@dtable).to_bson.to_s)
  end
  self
end