Created
September 30, 2016 10:32
-
-
Save Paxa/8f5ad74febc32246f468499fc1aac4ad to your computer and use it in GitHub Desktop.
Faster pagination for kaminari
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@payments_base = Payment.extending(FasterPagination) | |
@payments = @payments_base.page(params[:page]).per(20) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module FasterPagination | |
include Kaminari::ActiveRecordRelationMethods | |
include Kaminari::PageScopeMethods | |
def total_count(column_name = :all, options = {}) | |
return @total_count_cached if @total_count_cached | |
copy = except(:order, :includes) | |
copy.select_values = ['1'] | |
# copy.limit_value * 5 + 1 => means count only next 6 pages | |
# when call :count and qurey has "group by" it will return hash, | |
# execute_simple_calculation - always return a number | |
query_count = copy.limit(copy.limit_value * 5 + 1).send(:execute_simple_calculation, 'count', "1", false) | |
total_count = copy.offset_value + query_count | |
@total_count_cached = total_count | |
end | |
def per(num) | |
if (n = num.to_i) <= 0 | |
self | |
elsif max_per_page && max_per_page < n | |
limit(max_per_page).offset(offset_value / limit_value * max_per_page) | |
else | |
limit(n).offset(offset_value / limit_value * n) | |
end | |
end | |
def total_where_values | |
defaults = default_scopes.map(&:call) | |
(where_values + defaults.map(&:where_values)).flatten.uniq.map do |where_value| | |
next if where_value.blank? | |
where_value.is_a?(String) ? where_value : where_value.to_sql | |
end | |
end | |
def total_order_values | |
defaults = default_scopes.map(&:call) | |
(order_values + defaults.map(&:order_values)).flatten.uniq.map do |order_value| | |
next if order_value.blank? | |
order_value.is_a?(String) ? order_value : order_value.to_sql | |
end | |
end | |
eval <<-RUBY | |
def #{Kaminari.config.page_method_name}(num = nil) | |
limit(default_per_page).offset(default_per_page * ([num.to_i, 1].max - 1)) | |
end | |
RUBY | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment