Sha256: e8d9ec23cd3239ed791ef2b9389615e676d4c8a3f335b1fac3cbefce857871ba

Contents?: true

Size: 1.71 KB

Versions: 17

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

module ShopifyAPI
  class PaginatedCollection < ActiveResource::Collection
    module CollectionPagination
      def initialize(args)
        @next_url = pagination_link_headers.next_link&.url&.to_s
        @previous_url = pagination_link_headers.previous_link&.url&.to_s
        super(args)
      end

      def next_page?
        ensure_available
        @next_url.present?
      end

      def previous_page?
        ensure_available
        @previous_url.present?
      end

      def fetch_next_page
        fetch_page(@next_url)
      end

      def fetch_previous_page
        fetch_page(@previous_url)
      end

      def next_page_info
        extract_page_info(@next_url)
      end

      def previous_page_info
        extract_page_info(@previous_url)
      end

      private

      AVAILABLE_IN_VERSION = ShopifyAPI::ApiVersion.find_version('2019-10')
      AVAILABLE_IN_VERSION_EARLY = ShopifyAPI::ApiVersion.find_version('2019-07')

      def fetch_page(url)
        ensure_available
        return [] unless url.present?

        resource_class.all(from: url)
      end

      def pagination_link_headers
        @pagination_link_headers ||= ShopifyAPI::PaginationLinkHeaders.new(
          ShopifyAPI::Base.connection.response["Link"]
        )
      end

      def ensure_available
        return if ShopifyAPI::Base.api_version >= AVAILABLE_IN_VERSION
        return if ShopifyAPI::Base.api_version >= AVAILABLE_IN_VERSION_EARLY && resource_class.early_july_pagination?
        raise NotImplementedError
      end

      def extract_page_info(url)
        CGI.escape(Rack::Utils.parse_query(URI(url).query)['page_info']) if url.present?
      end
    end

    include CollectionPagination
  end
end

Version data entries

17 entries across 17 versions & 2 rubygems

Version Path
shopify_api-9.5.2 lib/shopify_api/paginated_collection.rb
ruby_shopify_api-1.2.0 lib/ruby_shopify_api/paginated_collection.rb
ruby_shopify_api-1.1.0 lib/shopify_api/paginated_collection.rb
ruby_shopify_api-1.0.0 lib/shopify_api/paginated_collection.rb
shopify_api-9.5.1 lib/shopify_api/paginated_collection.rb
shopify_api-9.5 lib/shopify_api/paginated_collection.rb
shopify_api-9.4.1 lib/shopify_api/paginated_collection.rb
shopify_api-9.4.0 lib/shopify_api/paginated_collection.rb
shopify_api-9.3.0 lib/shopify_api/paginated_collection.rb
shopify_api-9.2.0 lib/shopify_api/paginated_collection.rb
shopify_api-9.1.0 lib/shopify_api/paginated_collection.rb
shopify_api-9.0.4 lib/shopify_api/paginated_collection.rb
shopify_api-9.0.3 lib/shopify_api/paginated_collection.rb
shopify_api-9.0.2 lib/shopify_api/paginated_collection.rb
shopify_api-9.0.1 lib/shopify_api/paginated_collection.rb
shopify_api-9.0.0 lib/shopify_api/paginated_collection.rb
shopify_api-8.1.0 lib/shopify_api/paginated_collection.rb