Module: Ruson::Querying::ClassMethods

Defined in:
lib/ruson/querying.rb

Instance Method Summary collapse

Instance Method Details

#allObject



9
10
11
12
13
14
15
16
17
# File 'lib/ruson/querying.rb', line 9

def all
  ensure_output_folder_is_defined

  model_files.collect do |path|
    json = JSON.parse(File.read(path))

    new(json.merge(id: id_from_file_path(path)))
  end
end

#find(id) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/ruson/querying.rb', line 19

def find(id)
  ensure_output_folder_is_defined

  file_path = File.join(model_base_path, "#{id}.json")

  return unless File.exist?(file_path)

  load(file_path, id: id)
end

#find!(id) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/ruson/querying.rb', line 29

def find!(id)
  record = find(id)

  raise Ruson::RecordNotFound unless record

  record
end

#firstObject



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/ruson/querying.rb', line 37

def first
  ensure_output_folder_is_defined

  file_path = model_files.first

  return unless file_path

  id = id_from_file_path(file_path)

  load(file_path, id: id)
end

#first!Object



49
50
51
52
53
54
55
# File 'lib/ruson/querying.rb', line 49

def first!
  record = first

  raise Ruson::RecordNotFound unless record

  record
end

#load(file_path, extra_json = {}) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/ruson/querying.rb', line 57

def load(file_path, extra_json = {})
  json = JSON.parse(File.read(file_path))

  json.merge!(extra_json) if extra_json

  new json
end

#model_filesObject



85
86
87
# File 'lib/ruson/querying.rb', line 85

def model_files
  Dir.glob(File.join(model_base_path, '*.json'))
end

#where(attributes) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/ruson/querying.rb', line 65

def where(attributes)
  ensure_output_folder_is_defined

  query_attributes = attributes.stringify_keys

  models = model_files.collect do |path|
    json = JSON.parse(File.read(path))

    query_attributes_matches = query_attributes.keys.all? do |key|
      json[key] == query_attributes[key]
    end

    if query_attributes_matches
      new(json.merge(id: id_from_file_path(path)))
    end
  end.compact

  Array(models)
end