Skip to content

Commit 654e297

Browse files
committed
Don't load both Kaminari and will_paginate
It's possible users will have both `will_paginate` and `kaminari` as dependencies. Because the two are incompatible, avoid loading both and instead first attempt to load Kaminari. If that cannot load, then attempt to load will_paginate. Fixes #18. Signed-off-by: David Celis <[email protected]>
1 parent ac9a62a commit 654e297

File tree

1 file changed

+32
-13
lines changed

1 file changed

+32
-13
lines changed

lib/api-pagination/hooks.rb

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
module ApiPagination
22
class Hooks
3-
def self.init
3+
def self.init!
44
begin; require 'rails'; rescue LoadError; end
55
if defined?(ActionController::Base)
66
require 'rails/pagination'
@@ -19,22 +19,28 @@ def self.init
1919
Grape::API.send(:include, Grape::Pagination)
2020
end
2121

22-
begin; require 'will_paginate'; rescue LoadError; end
23-
if defined?(WillPaginate::CollectionMethods)
24-
WillPaginate::CollectionMethods.module_eval do
25-
def first_page?() !previous_page end
26-
def last_page?() !next_page end
27-
end
22+
# Kaminari and will_paginate conflict with each other, so we should check
23+
# to see if either is already active before attempting to load them.
24+
if defined?(Kaminari)
25+
initialize_kaminari! and return
26+
elsif defined?(WillPaginate::CollectionMethods)
27+
initialize_will_paginate! and return
28+
end
2829

29-
ApiPagination.instance_variable_set(:@paginator, :will_paginate)
30+
# If neither is loaded, we can safely attempt these requires.
31+
begin
32+
require 'kaminari'
33+
initialize_kaminari! and return
34+
rescue LoadError
3035
end
3136

32-
begin; require 'kaminari'; rescue LoadError; end
33-
if defined?(Kaminari)
34-
ApiPagination.instance_variable_set(:@paginator, :kaminari)
37+
begin
38+
require 'will_paginate'
39+
initialize_will_paginate! and return
40+
rescue LoadError
3541
end
3642

37-
STDERR.puts <<-EOC unless defined?(Kaminari) || defined?(WillPaginate)
43+
STDERR.puts <<-EOC
3844
Warning: api-pagination relies on either Kaminari or WillPaginate. Please
3945
install either dependency by adding one of the following to your Gemfile:
4046
@@ -43,7 +49,20 @@ def last_page?() !next_page end
4349
4450
EOC
4551
end
52+
53+
def self.initialize_kaminari!
54+
ApiPagination.instance_variable_set(:@paginator, :kaminari)
55+
end
56+
57+
def self.initialize_will_paginate!
58+
WillPaginate::CollectionMethods.module_eval do
59+
def first_page?() !previous_page end
60+
def last_page?() !next_page end
61+
end
62+
63+
ApiPagination.instance_variable_set(:@paginator, :will_paginate)
64+
end
4665
end
4766
end
4867

49-
ApiPagination::Hooks.init
68+
ApiPagination::Hooks.init!

0 commit comments

Comments
 (0)