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 Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDataStore

self



61
62
63
# File 'lib/stone/data_store.rb', line 61

def initialize
  @resources = {}
end

Class Attribute Details

.local_dirObject

Returns the value of attribute local_dir.



6
7
8
# File 'lib/stone/data_store.rb', line 6

def local_dir
  @local_dir
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



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

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



31
32
33
34
35
36
# File 'lib/stone/data_store.rb', line 31

def determine_save_method(obj, store)
  store.resources[obj.model].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



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/stone/data_store.rb', line 12

def load_data(sym)
  ymls = Dir.glob(self.local_dir/sym.to_s.pluralize/"*.yml").sort { |a,b| File.basename(a,".yml").to_i - File.basename(b,".yml").to_i }
  objs = []
  unless ymls.empty?
    ymls.each do |yml|
      obj = YAML.load_file yml
      objs << [obj.id, obj]
    end
  end
  return objs
end

.write_yaml(obj) ⇒ Object

Persist the object via YAML

Parameters

obj

The object to be persisted



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

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

Instance Method Details

#resourcesObject



65
66
67
# File 'lib/stone/data_store.rb', line 65

def resources
  @resources
end