Class: Jason::Encoding::PersistenceHandler::Restorable

Inherits:
Object
  • Object
show all
Includes:
Operations::File
Defined in:
lib/jason/encoding/restorable.rb

Instance Method Summary collapse

Instance Method Details

#all(*args) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/jason/encoding/restorable.rb', line 25

def all(*args)
  options = args.shift

  @klass = options[:klass]
  key = Jason::singularize_key(@klass)
  persisted_file_content = load_from_file(where_to_persist(@klass.name))
  r_objects = ActiveSupport::JSON.decode(persisted_file_content)
  r_objects.map do |obj|
    restore_with_cast(obj[key])
  end
end

#by_id(*args) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/jason/encoding/restorable.rb', line 9

def by_id(*args)
  options = args.shift

  @id = options[:id]
  @klass = options[:klass]
  key = Jason::singularize_key(@klass)
  persisted_file_content = load_from_file(where_to_persist(@klass.name))
  r_objects = ActiveSupport::JSON.decode(persisted_file_content)
  obj = r_objects.detect{|obj| obj[key]["id"] == @id}
  raise Jason::Errors::DocumentNotFoundError, "Document not found with id #{@id}." if obj.nil?
  
  return restore_with_cast(obj[key])
rescue MultiJson::DecodeError => de
  raise Jason::Errors::DocumentNotFoundError, "Document not found with id #{@id}."
end

#with_conditions(*args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/jason/encoding/restorable.rb', line 37

def with_conditions(*args)
  options = args.pop
  
  @klass = options[:klass]
  options.delete(:klass)
  key = Jason::singularize_key(@klass)

  persisted_file_content = load_from_file(where_to_persist(@klass.name))
  r_objects = ActiveSupport::JSON.decode(persisted_file_content)
  found_objects = []
  
  r_objects.each do |obj|
    if obj[key][options.keys.join.to_s] == options.values.join
      found_objects << restore_with_cast(obj[key])
    end
  end
  found_objects
end