Class: RubyFFDB::StorageEngines::JsonEngine

Inherits:
RubyFFDB::StorageEngine show all
Defined in:
lib/rffdb/storage_engines/json_engine.rb

Class Method Summary collapse

Methods inherited from RubyFFDB::StorageEngine

cache, cache_lookup, cache_provider, cache_size, cache_store, flush, index, index_lookup, index_update, next_id, read_lock, write_lock

Class Method Details

.all(type) ⇒ Object

Lazily grab all document ids in use



42
43
44
45
46
47
48
49
50
51
# File 'lib/rffdb/storage_engines/json_engine.rb', line 42

def self.all(type)
  directory_glob = read_lock(type) do
    Dir.glob(File.join(File.dirname(file_path(type, 0)), '*.json'))
  end
  if directory_glob and !directory_glob.empty?
    directory_glob.map { |doc| Integer(File.basename(doc, '.json')) }.sort
  else
    []
  end
end

.file_path(type, object_id) ⇒ Object



53
54
55
56
57
58
59
60
# File 'lib/rffdb/storage_engines/json_engine.rb', line 53

def self.file_path(type, object_id)
  File.join(
    DB_DATA,
    type.to_s.gsub('::', '__'),
    'documents',
    object_id.to_s + '.json'
  )
end

.retrieve(type, object_id, use_caching = true) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rffdb/storage_engines/json_engine.rb', line 23

def self.retrieve(type, object_id, use_caching = true)
  result = nil
  begin
    result = cache_lookup(type, object_id) if use_caching
    unless result
      read_lock(type) do
        file = File.open(file_path(type, object_id), 'r')
        result = JSON.load(file)
        file.close
      end
    end
    cache_store(type, object_id, result)
  rescue => e
    puts e.message
  end
  result.dup # Return a duplicate to support caching
end

.store(type, object_id, data) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rffdb/storage_engines/json_engine.rb', line 7

def self.store(type, object_id, data)
  path = file_path(type, object_id)
  write_lock(type) do
    FileUtils.mkdir_p(File.dirname(path))
    File.open(path, 'w') do |file|
      file.puts JSON.dump(data)
    end
    # Update all indexed columns
    type.structure.collect {|k,v| k if v[:index] }.compact.each do |col|
      index_update(type, col, object_id, data[col.to_s])
    end
    cache_store(type, object_id, data)
  end
  true
end