Skip to content

Instantly share code, notes, and snippets.

@Startouf
Created October 25, 2018 20:58

Revisions

  1. Startouf created this gist Oct 25, 2018.
    57 changes: 57 additions & 0 deletions in_memory_iterable_adapter.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    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