File tree Expand file tree Collapse file tree 2 files changed +28
-3
lines changed Expand file tree Collapse file tree 2 files changed +28
-3
lines changed Original file line number Diff line number Diff line change 3
3
module ApiPagination
4
4
protected
5
5
def paginate ( scope )
6
+ links = ( headers [ 'Link' ] || "" ) . split ( ',' ) . map ( &:strip )
7
+
6
8
scope = instance_variable_get ( :"@#{ scope } " )
7
9
url = request . original_url . sub ( /\? .*$/ , '' )
8
10
pages = { }
@@ -17,9 +19,9 @@ def paginate(scope)
17
19
pages [ :next ] = scope . current_page + 1
18
20
end
19
21
20
- links = pages . map do |k , v |
22
+ pages . each do |k , v |
21
23
new_params = request . query_parameters . merge ( { :page => v } )
22
- %(<#{ url } ?#{ new_params . to_param } >; rel="#{ k } ")
24
+ links << %(<#{ url } ?#{ new_params . to_param } >; rel="#{ k } ")
23
25
end
24
26
25
27
headers [ 'Link' ] = links . join ( ', ' ) unless links . empty?
Original file line number Diff line number Diff line change @@ -24,6 +24,13 @@ class NumbersController < ActionController::Base
24
24
def index
25
25
page = params . fetch ( :page , 1 ) . to_i
26
26
total = params . fetch ( :count ) . to_i
27
+
28
+ if params [ :with_headers ]
29
+ query = request . query_parameters
30
+ query . delete ( :with_headers )
31
+ headers [ 'Link' ] = %(<#{ numbers_url } ?#{ query . to_param } >; rel="without") if params [ :with_headers ]
32
+ end
33
+
27
34
@numbers = PaginatedSet . new ( page , total )
28
35
render json : @numbers
29
36
end
@@ -34,7 +41,23 @@ def index
34
41
context 'without enough items to give more than one page' do
35
42
it 'should not paginate' do
36
43
get :index , count : 20
37
- response . headers . keys . should_not include ( "Link" )
44
+ response . headers . keys . should_not include ( 'Link' )
45
+ end
46
+ end
47
+
48
+ context 'with existing Link headers' do
49
+ before ( :each ) do
50
+ get :index , count : 30 , with_headers : true
51
+ @links = response . headers [ 'Link' ] . split ( ', ' )
52
+ end
53
+
54
+ it 'should keep existing Links' do
55
+ @links . should include ( '<http://test.host/numbers?count=30>; rel="without"' )
56
+ end
57
+
58
+ it 'should contain pagination Links' do
59
+ @links . should include ( '<http://test.host/numbers?count=30&page=2>; rel="next"' )
60
+ @links . should include ( '<http://test.host/numbers?count=30&page=2>; rel="last"' )
38
61
end
39
62
end
40
63
You can’t perform that action at this time.
0 commit comments