Sha256: a3ed1bdd467b827ee3fb6cc7c96089a99752b3b11dcb5eb235a7e6ebc9fb56a3

Contents?: true

Size: 1.85 KB

Versions: 3

Compression:

Stored size: 1.85 KB

Contents

module EventbriteSDK
  class ResourceList
    extend Forwardable
    include Enumerable

    def_delegators :@objects, :[], :each, :empty?

    def initialize(
      url_base: nil,
      object_class: nil,
      key: nil,
      query: {},
      request: EventbriteSDK
    )
      @key = key
      @object_class = object_class
      @objects = []
      @query = query
      @request = request
      @url_base = url_base
    end

    def concat(other)
      other.concat(to_ary)
    end

    def retrieve(query: {})
      @query.merge!(query)
      load_response

      self
    end

    def page(num)
      pagination['page_number'] = num

      retrieve
    end

    def next_page
      pagination['page_number'] += 1 unless page_number >= (page_count || 1)

      retrieve
    end

    def prev_page
      pagination['page_number'] -= 1 unless page_number <= 1

      retrieve
    end

    %w(object_count page_number page_size page_count).each do |method|
      define_method(method) { pagination[method] }
    end

    def to_ary
      objects
    end

    def to_json(opts = {})
      { key => objects.map(&:to_h), 'pagination' => @pagination }.to_json(opts)
    end

    def with_expansion(*args)
      if args.first
        @query[:expand] = args.join(',')
      else
        @query.delete(:expand)
      end

      self
    end

    private

    def pagination
      @pagination ||= { 'page_count' => 1, 'page_number' => 1 }
    end

    def load_response
      response = request.get(
        url: url_base,
        query: query.merge(page: page_number)
      )

      @objects = (response[key.to_s] || []).map { |raw| object_class.new(raw) }
      @pagination = response['pagination']
    end

    attr_reader :expansion,
                :key,
                :object_class,
                :objects,
                :query,
                :request,
                :url_base
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
eventbrite_sdk-3.0.11 lib/eventbrite_sdk/resource_list.rb
eventbrite_sdk-3.0.10 lib/eventbrite_sdk/resource_list.rb
eventbrite_sdk-3.0.9 lib/eventbrite_sdk/resource_list.rb