Sha256: 7c37fab63e0d7573a63c1034a54e3ad0b286e82a8b38b6faba1404809be10aba

Contents?: true

Size: 1.76 KB

Versions: 3

Compression:

Stored size: 1.76 KB

Contents

require 'will_paginate/active_record'

# add `:large` option with make pagination on large tables easier, because `SELECT *` is slow with large `OFFSET`:
#   first it fetch ids of the records using `SELECT id`
#   and in the second query it fetch records
module WillPaginate
  module ActiveRecord
    module RelationMethods
      attr_accessor :paginate_limit, :paginate_offset

      def per_page(value = nil)
        if value.nil?
          paginate_limit || limit_value
        else
          limit(value.to_i)
        end
      end

      def offset(value = nil)
        if value.nil?
          paginate_offset || offset_value
        else
          super(value.to_i)
        end
      end
    end

    module Pagination
      def paginate(options)
        options = options.dup
        page_number = [1, options[:page].to_i].max
        per_page = (options.delete(:per_page) || self.per_page).to_i
        total = options.delete(:total_entries)
        large = options.delete(:large)

        count_options = options.delete(:count)
        options.delete(:page)

        rel = limit(per_page.to_i).page(page_number)
        rel = rel.apply_finder_options(options) if options.any?
        rel.wp_count_options = count_options if count_options
        rel.total_entries = total.to_i unless total.blank?

        if large
          ids = rel.except(:includes).pluck(Arel.sql("#{quoted_table_name}.#{primary_key}"))
          new_rel = rel.except(:limit, :offset, :where).where(primary_key => ids)
          new_rel.paginate_limit = rel.limit_value.to_i
          new_rel.paginate_offset = rel.offset_value.to_i
          new_rel.total_entries = rel.total_entries
          new_rel.current_page = rel.current_page
          new_rel
        else
          rel
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ab_admin-0.11.0 lib/ab_admin/hooks/will_paginate_id_prefetch.rb
ab_admin-0.10.0 lib/ab_admin/hooks/will_paginate_id_prefetch.rb
ab_admin-0.9.0 lib/ab_admin/hooks/will_paginate_id_prefetch.rb