File: pagination.rb

package info (click to toggle)
ruby-gh 0.21.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,644 kB
  • sloc: ruby: 1,793; makefile: 4
file content (64 lines) | stat: -rw-r--r-- 1,365 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# frozen_string_literal: true

module GH
  class Pagination < Wrapper
    class Paginated
      include Enumerable

      def initialize(page, url, gh)
        @page = page
        @next_url = url
        @gh = gh
      end

      def each(&block)
        return enum_for(:each) unless block

        @page.each(&block)
        next_page.each(&block)
      end

      def inspect
        "[#{first.inspect}, ...]"
      end

      def [](value)
        raise TypeError, "index has to be an Integer, got #{value.class}" unless value.is_a? Integer
        return @page[value] if value < @page.size

        next_page[value - @page.size]
      end

      def to_ary
        to_a # replace with better implementation (use in_parallel)
      end

      def headers
        @page.headers
      end

      private

      def next_page
        @next_page ||= @gh[@next_url]
      end
    end

    wraps GH::Normalizer
    double_dispatch

    def fetch_resource(key)
      url = frontend.full_url(key)
      params = url.query_values || {}
      params['per_page'] ||= 100
      url.query_values = params
      super url.request_uri
    end

    def modify_response(response)
      return response unless response.respond_to?(:to_ary) && response.headers['link'] =~ (/<([^>]+)>;\s*rel="next"/)

      Paginated.new(response, ::Regexp.last_match(1), self)
    end
  end
end