Skip to content

Commit fe9309f

Browse files
committed
Don't override previously-set Link headers
If any Links were provided in the header before api-pagination does its stuff, don't override them. Extract any Links that already exist and append pagination Links to the list. Signed-off-by: David Celis <[email protected]>
1 parent 81777bd commit fe9309f

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

lib/api-pagination.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
module ApiPagination
44
protected
55
def paginate(scope)
6+
links = (headers['Link'] || "").split(',').map(&:strip)
7+
68
scope = instance_variable_get(:"@#{scope}")
79
url = request.original_url.sub(/\?.*$/, '')
810
pages = {}
@@ -17,9 +19,9 @@ def paginate(scope)
1719
pages[:next] = scope.current_page + 1
1820
end
1921

20-
links = pages.map do |k, v|
22+
pages.each do |k, v|
2123
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}")
2325
end
2426

2527
headers['Link'] = links.join(', ') unless links.empty?

spec/controllers/numbers_controller_spec.rb

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ class NumbersController < ActionController::Base
2424
def index
2525
page = params.fetch(:page, 1).to_i
2626
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+
2734
@numbers = PaginatedSet.new(page, total)
2835
render json: @numbers
2936
end
@@ -34,7 +41,23 @@ def index
3441
context 'without enough items to give more than one page' do
3542
it 'should not paginate' do
3643
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"')
3861
end
3962
end
4063

0 commit comments

Comments
 (0)