Created
October 25, 2018 20:58
-
-
Save Startouf/5cefc1d79bda0c99160190286c0e0ffe to your computer and use it in GitHub Desktop.
jsonapi_suite for In memory Iterables adapter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment