@@ -3,7 +3,6 @@ module Adapter
3
3
class JsonApi < Base
4
4
class PaginationLinks
5
5
MissingSerializationContextError = Class . new ( KeyError )
6
- FIRST_PAGE = 1
7
6
8
7
attr_reader :collection , :context
9
8
@@ -20,12 +19,13 @@ def initialize(collection, adapter_options)
20
19
end
21
20
22
21
def as_json
23
- per_page = collection . try ( :per_page ) || collection . try ( :limit_value ) || collection . size
24
- pages_from . each_with_object ( { } ) do |( key , value ) , hash |
25
- params = query_parameters . merge ( page : { number : value , size : per_page } ) . to_query
26
-
27
- hash [ key ] = "#{ url ( adapter_options ) } ?#{ params } "
28
- end
22
+ {
23
+ "self" : location_url ,
24
+ "first" : first_page_url ,
25
+ "prev" : prev_page_url ,
26
+ "next" : next_page_url ,
27
+ "last" : last_page_url
28
+ }
29
29
end
30
30
31
31
protected
@@ -34,37 +34,37 @@ def as_json
34
34
35
35
private
36
36
37
- def pages_from
38
- { } . tap do |pages |
39
- pages [ :self ] = collection . current_page
40
- pages [ :first ] = FIRST_PAGE
41
- pages [ :last ] = collection . total_pages
37
+ def location_url
38
+ url_for_page ( collection . current_page )
39
+ end
42
40
43
- if collection . total_pages > 0
44
- unless collection . current_page == FIRST_PAGE
45
- pages [ :prev ] = collection . current_page - FIRST_PAGE
46
- end
41
+ def first_page_url
42
+ url_for_page ( 1 )
43
+ end
47
44
48
- unless collection . current_page == collection . total_pages
49
- pages [ :next ] = collection . current_page + FIRST_PAGE
50
- end
51
- else
52
- pages [ :last ] = FIRST_PAGE
53
- end
54
- end
45
+ def prev_page_url
46
+ return nil if collection . first_page?
47
+ url_for_page ( collection . prev_page )
55
48
end
56
49
57
- def url ( options )
58
- @url ||= options . fetch ( :links , { } ) . fetch ( :self , nil ) || request_url
50
+ def next_page_url
51
+ return nil if collection . last_page? || collection . out_of_range?
52
+ url_for_page ( collection . next_page )
59
53
end
60
54
61
- def request_url
62
- @request_url ||= context . request_url
55
+ def url_for_page ( number )
56
+ params = query_parameters . dup
57
+ params [ :page ] = { page : per_page , number : number }
58
+ context . url_for ( action : :index , params : params )
63
59
end
64
60
65
61
def query_parameters
66
62
@query_parameters ||= context . query_parameters
67
63
end
64
+
65
+ def per_page
66
+ @per_page ||= collection . try ( :per_page ) || collection . try ( :limit_value ) || collection . size
67
+ end
68
68
end
69
69
end
70
70
end
0 commit comments