ministryofjustice/Claim-for-Crown-Court-Defence

View on GitHub
app/services/remote/base.rb

Summary

Maintainability
A
0 mins
Test Coverage
B
88%
module Remote
  class Base
    include ActiveModel::Model
    include Remote::SimpleAssociations

    attr_accessor :id, :uuid, :created_at, :updated_at

    def remote?
      true
    end

    def persisted?
      true
    end

    class << self
      def resource_path
        raise 'not implemented'
      end

      def all(**)
        result = client.get(resource_path, **)
        parse_result(result)
      end

      def find(id)
        all.detect { |m| m.id == id }
      end

      private

      def client
        Remote::HttpClient.instance
      end

      def parse_result(result)
        result = { items: result } unless result.is_a?(Hash)
        pagination = result.fetch(:pagination, {})
        collection = result.fetch(:items, result).map { |attrs| new(attrs) }

        Remote::Collections::PaginatedCollection.new(collection, pagination)
      end
    end
  end
end