Class: Stone::DataStore

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

Overview

An in-memory representation of the file-based datastore

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDataStore

self



71
72
73
# File 'lib/stone/data_store.rb', line 71

def initialize
  @resources = {}
end

Class Method Details

.delete(id, klass_dir) ⇒ Object

Removes object’s yaml file

Parameters

id

id of the object to be removed

klass_dir

directory in which object resides



62
63
64
65
66
67
68
# File 'lib/stone/data_store.rb', line 62

def delete(id, klass_dir)
  raise "Object could not be found" \
    unless File.exists?(self.local_dir/klass_dir/"#{id}.yml")
      
  FileUtils.remove_file(self.local_dir/klass_dir/"#{id}.yml")
  true
end

.determine_save_method(obj, store) ⇒ Object

If the object already exists (id was found), this returns put(update), else post(create)

Parameters

obj

The instantiated resource to be saved

store

DataStore object



41
42
43
44
45
46
# File 'lib/stone/data_store.rb', line 41

def determine_save_method(obj, store)
  store.resources[obj.class.to_s.make_key].each do |o|
    return :put if o[0] == obj.id
  end
  :post
end

.load_data(sym) ⇒ Object

Loads yaml files specific to the resource represented by sym

Parameters

sym

Symbol representing resource data to load



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/stone/data_store.rb', line 21

def load_data(sym)
  dir = self.local_dir
  ymls = Dir.glob(dir/sym.to_s.pluralize/"*.yml")
  objs = []
  unless ymls.empty?
    ymls.each do |yml|
      obj = YAML.load_file yml
      objs << [obj.id, obj]
    end
  end
  return objs
end

.local_dirObject

Provides the directory path to the local (app-specific) datastore



13
14
15
# File 'lib/stone/data_store.rb', line 13

def local_dir
  @dir || Dir.pwd/"datastore"
end

.local_dir=(value) ⇒ Object

:nodoc:



8
9
10
# File 'lib/stone/data_store.rb', line 8

def local_dir=(value) #:nodoc:
  @dir = value
end

.write_yaml(obj) ⇒ Object

Persist the object via YAML

Parameters

obj

The object to be persisted



51
52
53
54
55
56
# File 'lib/stone/data_store.rb', line 51

def write_yaml(obj)
  path = self.local_dir/obj.class.to_s.downcase.pluralize/"#{obj.id}.yml"
  File.open(path, 'w') do |out|
    YAML.dump(obj, out)
  end
end

Instance Method Details

#resourcesObject



75
76
77
# File 'lib/stone/data_store.rb', line 75

def resources
  @resources
end