Class: Ambry::Adapters::File

Inherits:
Ambry::Adapter show all
Defined in:
lib/ambry/adapters/file.rb

Overview

Loads and saves hash database from a Marshal.dump file.

Direct Known Subclasses

YAML

Instance Attribute Summary collapse

Attributes inherited from Ambry::Adapter

#db, #name, #read_only

Instance Method Summary collapse

Methods inherited from Ambry::Adapter

#db_for, #read_only?

Constructor Details

#initialize(options) ⇒ File

Returns a new instance of File.


9
10
11
12
13
14
# File 'lib/ambry/adapters/file.rb', line 9

def initialize(options)
  @file_path = options[:file]
  @read_only  = !! options[:read_only]
  @lock      = Mutex.new
  super
end

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path


6
7
8
# File 'lib/ambry/adapters/file.rb', line 6

def file_path
  @file_path
end

#lockObject (readonly)

Returns the value of attribute lock


7
8
9
# File 'lib/ambry/adapters/file.rb', line 7

def lock
  @lock
end

Instance Method Details

#export_dataObject


24
25
26
# File 'lib/ambry/adapters/file.rb', line 24

def export_data
  Marshal.dump(db)
end

#import_dataObject


28
29
30
31
# File 'lib/ambry/adapters/file.rb', line 28

def import_data
  data = ::File.open(file_path, "rb") { |f| f.read }
  Marshal.load(data)
end

#load_databaseObject


16
17
18
19
20
21
22
# File 'lib/ambry/adapters/file.rb', line 16

def load_database
  @db = import_data
  (!@db || @db.empty?) ? @db = {} : @db.map(&:freeze)
rescue Errno::ENOENT
  # @TODO warn via logger when file doesn't exist
  @db = {}
end

#save_databaseObject


33
34
35
36
37
38
# File 'lib/ambry/adapters/file.rb', line 33

def save_database
  super
  @lock.synchronize do
    ::File.open(file_path, "wb") {|f| f.write(export_data)}
  end
end