lib/ticketing_hub/collection.rb in ticketinghub-1.0.9 vs lib/ticketing_hub/collection.rb in ticketinghub-1.1.0

- old
+ new

@@ -1,37 +1,63 @@ +require_relative 'resource' + module TicketingHub class Collection < Enumerator::Generator + attr_accessor :client, :path, :options, :klass - attr_accessor :client, :path, :options - - def initialize(client, path, options = {}) + 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 << value } - else yielder << response.body end + 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 << value } + 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 count + client.request(:get, "#{path}/count", options).body.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? - client.request(:get, "#{path}/#{id}", options).body + _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 \ No newline at end of file