Class: Memoh::DB::JSONAdapter

Inherits:
AbstractAdapter show all
Defined in:
lib/memoh/db/json_adapter.rb

Overview

:nodoc:

Constant Summary collapse

DIRECTORY =
File.expand_path("~/.memoh")
FILE_PATH =
File.expand_path("#{DIRECTORY}/memoh_db.json")

Instance Method Summary collapse

Methods inherited from AbstractAdapter

#find_by

Constructor Details

#initialize(persisted_class) ⇒ JSONAdapter

Returns a new instance of JSONAdapter.



13
14
15
16
# File 'lib/memoh/db/json_adapter.rb', line 13

def initialize(persisted_class)
  @persisted_class = persisted_class
  Dir.mkdir(DIRECTORY) unless Dir.exist?(DIRECTORY)
end

Instance Method Details

#allObject



18
19
20
21
22
23
# File 'lib/memoh/db/json_adapter.rb', line 18

def all
  @objects ||= begin
    retrieved_json = File.exist?(FILE_PATH) ? JSON.parse(File.read(FILE_PATH)) : []
    retrieved_json.map { |obj| @persisted_class.new.from_json(obj.to_json) }
  end
end

#create(obj) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/memoh/db/json_adapter.rb', line 25

def create(obj)
  current_objs = all
  current_objs << obj

  File.open(FILE_PATH, "w") do |f|
    f.write(current_objs.to_json)
  end
end

#delete(obj) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/memoh/db/json_adapter.rb', line 46

def delete(obj)
  current_objs = all
  current_objs.reject! { |co| obj.send(@persisted_class.id_field) == co.send(@persisted_class.id_field) }

  File.open(FILE_PATH, "w") do |f|
    f.write(current_objs.to_json)
  end
end

#update(obj) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/memoh/db/json_adapter.rb', line 34

def update(obj)
  current_objs = all
  index = current_objs.find_index do |memo|
    memo.send(@persisted_class.id_field) == memo.send("#{@persisted_class.id_field}_was")
  end
  current_objs[index] = obj

  File.open(FILE_PATH, "w") do |f|
    f.write(current_objs.to_json)
  end
end