lib/githu3/resource_collection.rb in githu3-0.0.3 vs lib/githu3/resource_collection.rb in githu3-0.0.4

- old
+ new

@@ -1,16 +1,17 @@ require 'forwardable' +require 'digest/sha1' module Githu3 class ResourceCollection include Enumerable extend Forwardable - def_delegators :@resources, :each, :map, :<<, :length, :sort_by, :select, :detect, :find, :collect + def_delegators :@resources, :each, :map, :<<, :length, :sort_by, :select, :detect, :find, :collect, :first, :last - attr_reader :url, :fetch_error, :pagination + attr_reader :url, :fetch_error, :pagination, :current_page def initialize client, resource_klass, url, params={}, opts={} @resource_klass = resource_klass @url = url @params = params @@ -23,10 +24,11 @@ fetch self end def fetch(page=nil) + page = page || @current_page unless @current_page == 1 begin params = @params.dup.stringify_keys params["page"] = page unless page.nil? res = @client.get(@url, :params => params) update_pagination(res, params) @@ -43,27 +45,42 @@ end end def update_pagination(res, params) @pagination = parse_link_header(res.headers['link']) - @current_page = params["page"].to_i + @current_page = [1, params["page"].to_i].max + @last_page = @pagination['last'] unless @pagination['last'].nil? end def fetch_next - return [] unless @pagination["next"] - fetch(@pagination["next"]) + return [] if (@current_page + 1) > @last_page + fetch(@current_page + 1) end def fetch_prev - return [] unless @pagination["prev"] - fetch(@pagination["prev"]) + return [] if @current_page == 1 + fetch(@current_page - 1) end def fetch_last - return false unless @pagination["last"] - fetch(@pagination["last"]) + return [] unless @pagination["last"] + fetch(@last_page) end + + def fetch_first + fetch(1) + end + def next_page + np = @current_page + 1 + np < @last_page ? np : nil + end + + def prev_page + pp = @current_page - 1 + pp > 1 ? pp : nil + end + def parse_link_header src return {} if src.nil? links = src.scan(/<http[^<]+/i) return [] if links.nil? \ No newline at end of file