module Jsonapi
module Adapters
# Adapter for resources already loaded in memory
#
# The scope is meant to be something like an Array or Iterable of objects
#
# @example Time Series
#
# scope = [
# OpenStruct.new(at: Time.now.noon, name: 'I ate'),
# OpenStruct.new(at: Time.now.midnight, name: 'I went to sleep')
# ]
#
# Sorting by time
# scope.sort_by(&:at)
# Filtering by event name
# scope.select { |i| i.name == 'I ate' }
#
# @author [Cyril]
#
class InMemoryIterableAdapter < TransactionlessMongoidAdapter
# @override
def resolve(scope)
scope
end
# @override for array sort
def filter(scope, attribute, value)
scope.select do |item|
item.send(attribute) == value
end
end
# @Override
def order(scope, attribute, direction)
# return scope if attribute == :id # Seems broken
if direction == :asc
scope.sort_by { |i| i.public_send(attribute) }
elsif direction == :desc
scope.sort_by { |i| i.public_send(attribute) }.reverse
end
end
# @Override
def paginate(scope, current_page, per_page)
pg_start = (current_page - 1) * per_page
pg_eng = (current_page) * per_page - 1
scope[pg_start..pg_eng]
end
# @Override
def count(scope, _attr)
scope.size
end
end
end
end