Skip to content

Commit

Permalink
Merge pull request #91 from digitaltom/master
Browse files Browse the repository at this point in the history
add config option for base_url
  • Loading branch information
davidcelis authored Jan 11, 2018
2 parents c9fea97 + 58626b1 commit a5bd689
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
3 changes: 3 additions & 0 deletions lib/api-pagination/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ class Configuration

attr_accessor :include_total

attr_accessor :base_url

def configure(&block)
yield self
end
Expand All @@ -17,6 +19,7 @@ def initialize
@per_page_header = 'Per-Page'
@page_header = nil
@include_total = true
@base_url = nil
end

['page', 'per_page'].each do |param_name|
Expand Down
9 changes: 7 additions & 2 deletions lib/rails/pagination.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ def _paginate_collection(collection, options={})

collection = ApiPagination.paginate(collection, options)

links = (headers['Link'] || "").split(',').map(&:strip)
url = request.original_url.sub(/\?.*$/, '')
links = (headers['Link'] || '').split(',').map(&:strip)
url = base_url + request.path_info
pages = ApiPagination.pages_from(collection)

pages.each do |k, v|
Expand Down Expand Up @@ -58,5 +58,10 @@ def total_count(collection, options)
end
total_count || ApiPagination.total_from(collection)
end

def base_url
ApiPagination.config.base_url || request.base_url
end

end
end
15 changes: 14 additions & 1 deletion spec/rails_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,23 @@
ApiPagination.config.total_header = 'X-Total-Count'
ApiPagination.config.per_page_header = 'X-Per-Page'
ApiPagination.config.page_header = 'X-Page'
ApiPagination.config.base_url = 'http://guybrush:3000'

get :index, params: {count: 10}
get :index, params: params
end

after do
ApiPagination.config.total_header = 'Total'
ApiPagination.config.per_page_header = 'Per-Page'
ApiPagination.config.page_header = nil
ApiPagination.config.base_url = nil
end

let(:params) { { count: 10 } }
let(:total) { response.header['X-Total-Count'].to_i }
let(:per_page) { response.header['X-Per-Page'].to_i }
let(:page) { response.header['X-Page'].to_i }
let(:link) { response.header['Link'] }

it 'should give a X-Total-Count header' do
headers_keys = response.headers.keys
Expand All @@ -110,6 +114,15 @@
expect(headers_keys).to include('X-Page')
expect(page).to eq(1)
end

context 'with paginated result' do
let(:params) { { count: 20 } }
it 'should use custom base_url in the Link header' do

expect(response.headers['Link']).to eq(
'<http://guybrush:3000/numbers?count=20&page=2>; rel="last", <http://guybrush:3000/numbers?count=20&page=2>; rel="next"')
end
end
end

context 'configured not to include the total' do
Expand Down

0 comments on commit a5bd689

Please sign in to comment.