Class: Marvin::DataStore

Inherits:
Object
  • Object
show all
Defined in:
lib/marvin/data_store.rb

Overview

Implements a simple datastore interface, designed to make it easy to develop handlers which have persistent data.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ DataStore

Returns a new instance of DataStore.



44
45
46
47
48
# File 'lib/marvin/data_store.rb', line 44

def initialize(name)
  self.name = name.to_s
  self.registered_stores ||= {}
  self.registered_stores[self.name] ||= {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &blk) ⇒ Object



58
59
60
61
62
63
64
65
66
# File 'lib/marvin/data_store.rb', line 58

def method_missing(name, *args, &blk)
  if name.to_s =~ /^(.*)=$/i
    self[$1.to_s] = args.first
  elsif self.registered_stores[self.name].has_key?(name.to_s)
    return self.registered_stores[self.name][name.to_s]
  else
    super(name, *args, &blk)
  end
end

Instance Attribute Details

#nameObject

For each individual datastore.



42
43
44
# File 'lib/marvin/data_store.rb', line 42

def name
  @name
end

Class Method Details

.datastore_locationObject

Returns the path to the data store relative to this file. Used when loading / dumping the data.



14
15
16
17
# File 'lib/marvin/data_store.rb', line 14

def self.datastore_location
  path =  Marvin::Settings[:datastore_location] ? Marvin::Settings.datastore_location : "tmp/datastore.json"
  return Marvin::Settings.root / path
end

.dump!Object

Dump the current data store contents to file.



20
21
22
23
24
# File 'lib/marvin/data_store.rb', line 20

def self.dump!
  File.open(self.datastore_location, "w+") do |f|
    f.write self.registered_stores.to_json
  end
end

.load!Object

Load the current data store contents from file.



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/marvin/data_store.rb', line 27

def self.load!
  results = {}
  if File.exists?(self.datastore_location)
    begin
      json = JSON.load(File.read(self.datastore_location))
      results = json if json.is_a?(Hash)
    rescue JSON::ParserError
    end
  end
  self.registered_stores = results
end

Instance Method Details

#[](key) ⇒ Object



50
51
52
# File 'lib/marvin/data_store.rb', line 50

def [](key)
  ((self.registered_stores||={})[self.name]||={})[key.to_s]
end

#[]=(key, value) ⇒ Object



54
55
56
# File 'lib/marvin/data_store.rb', line 54

def []=(key,value)
  self.registered_stores[self.name][key.to_s] = value
end

#to_hashObject



68
69
70
# File 'lib/marvin/data_store.rb', line 68

def to_hash
  self.registered_stores[self.name]
end