Sha256: c34bad166a1fdc8a1fa8354dd58cf32435b175f78085c7066ae0b40be9a4782d

Contents?: true

Size: 1.96 KB

Versions: 7

Compression:

Stored size: 1.96 KB

Contents

require_relative 'base_resource'
require_relative 'array_like'

module Contentful
  # Resource Class for Arrays (e.g. search results)
  # @see _ https://www.contentful.com/developers/documentation/content-delivery-api/#arrays
  # @note It also provides an #each method and includes Ruby's Enumerable module (gives you methods like #min, #first, etc)
  class Array < BaseResource
    # @private
    DEFAULT_LIMIT = 100

    include Contentful::ArrayLike

    attr_reader :total, :limit, :skip, :items, :endpoint

    def initialize(item = nil,
                   configuration = {
                     default_locale: Contentful::Client::DEFAULT_CONFIGURATION[:default_locale]
                   },
                   endpoint = '', *)
      super(item, configuration)

      @endpoint = endpoint
      @total = item.fetch('total', nil)
      @limit = item.fetch('limit', nil)
      @skip = item.fetch('skip', nil)
      @items = item.fetch('items', [])
    end

    # @private
    def marshal_dump
      super.merge(endpoint: endpoint)
    end

    # @private
    def marshal_load(raw_object)
      super
      @endpoint = raw_object[:endpoint]
      @total = raw.fetch('total', nil)
      @limit = raw.fetch('limit', nil)
      @skip = raw.fetch('skip', nil)
      @items = raw.fetch('items', []).map do |item|
        require_relative 'resource_builder'
        ResourceBuilder.new(
          item.raw,
          raw_object[:configuration].merge(includes_for_single: Support.includes_from_response(raw, false)),
          item.respond_to?(:localized) ? item.localized : false
        ).run
      end
    end

    # @private
    def inspect
      "<#{repr_name} total=#{total} skip=#{skip} limit=#{limit}>"
    end

    # Simplifies pagination
    #
    # @return [Contentful::Array, false]
    def next_page(client = nil)
      return false if client.nil?

      new_skip = (skip || 0) + (limit || DEFAULT_LIMIT)
      client.send(endpoint.delete('/'), limit: limit, skip: new_skip)
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
contentful-2.5.0 lib/contentful/array.rb
contentful-2.4.0 lib/contentful/array.rb
contentful-2.3.0 lib/contentful/array.rb
contentful-2.2.2 lib/contentful/array.rb
contentful-2.2.1 lib/contentful/array.rb
contentful-2.2.0 lib/contentful/array.rb
contentful-2.1.3 lib/contentful/array.rb