module Ruson::Querying::ClassMethods

Public Instance Methods

all() click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# File lib/ruson/querying.rb, line 29
def find!(id)
  record = find(id)

  raise Ruson::RecordNotFound unless record

  record
end
first() click to toggle source
# 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!() click to toggle source
# File lib/ruson/querying.rb, line 49
def first!
  record = first

  raise Ruson::RecordNotFound unless record

  record
end
load(file_path, extra_json = {}) click to toggle source
# 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_files() click to toggle source
# File lib/ruson/querying.rb, line 85
def model_files
  Dir.glob(File.join(model_base_path, '*.json'))
end
where(attributes) click to toggle source
# 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