Sha256: 36e807c2a6451a5425fdc6a878b8125b0366730734bce469d29861391a6a8d38

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

require_relative 'resource'

module TicketingHub
  class Collection < Enumerator::Generator
    attr_accessor :client, :path, :options, :klass

    def initialize(client, path, options = {}, klass = nil)
      self.client = client
      self.path = path
      self.options = options
      self.klass = klass

      super() do |yielder|
        response = client.request(:get, path, options)
        if response.body.is_a?(Array)
          response.body.each { |value| yielder << _filter_value(value) }
        else yielder << _filter_value(response.body) end
        while next_url = links(response)['next']
          response = client.request(:get, next_url, options)
          response.body.each { |value| yielder << _filter_value(value) }
        end
      end
    end

    def limit value
      options.merge! limit: value.to_i
    end

    def offset value
      options.merge! offset: value.to_i
    end

    def create options = {}
      _filter_value client.request(:post, "#{path}", options).body
    end

    def find(id=nil, options = {}, &block)
      return super(&block) if block_given?
      _filter_value client.request(:get, "#{path}/#{id}", options).body
    end

    def links(response)
      links = ( response.headers["Link"] || "" ).split(', ').map do |link|
        url, type = link.match(/<(.*?)>; rel="(\w+)"/).captures
        [ type, url ]
      end

      Hash[*links.flatten]
    end

    private

      def _filter_value value
        unless klass.nil?
          return klass.new client, value, path, value.id
        else value end
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ticketinghub-1.1.1 lib/ticketing_hub/collection.rb