module SmartPaginate::ActiveRecordExtension::RelationMethods

Attributes

current_page[RW]
per_page[RW]

Public Instance Methods

count(*args) click to toggle source

Override count: make it return the number of entries that we expect

Calls superclass method
# File lib/smart_paginate/active_record_extension.rb, line 26
def count(*args)
  if limit_value && per_page && limit_value > per_page
    rel = except(:limit).limit(per_page)
    rel.count(*args)
  else
    super(*args)
  end
end
empty?() click to toggle source

Override empty: check fetched records instead of counting

# File lib/smart_paginate/active_record_extension.rb, line 36
def empty?
  load # make sure we have determined the number of fetched records

  @number_of_records.zero?
end
load() click to toggle source

Override load: fetch/slice records and determine number of records

Calls superclass method
# File lib/smart_paginate/active_record_extension.rb, line 43
def load
  super
  slice_records!

  self
end
next_page() click to toggle source
# File lib/smart_paginate/active_record_extension.rb, line 60
def next_page
  current_page + 1 if next_page?
end
next_page?() click to toggle source
# File lib/smart_paginate/active_record_extension.rb, line 50
def next_page?
  load # make sure we have determined the number of fetched records

  @number_of_records > per_page # there's a next page when we've fetched more records than per_page
end
previous_page() click to toggle source
# File lib/smart_paginate/active_record_extension.rb, line 64
def previous_page
  current_page - 1 if previous_page?
end
previous_page?() click to toggle source
# File lib/smart_paginate/active_record_extension.rb, line 56
def previous_page?
  current_page > 1
end
total_entries() click to toggle source
# File lib/smart_paginate/active_record_extension.rb, line 72
def total_entries
  @total_entries ||= begin
    load # make sure we have determined the number of fetched records

    # if we know that there are no more records, then we can calculate total_entries
    if (current_page == 1 || @number_of_records > 0) && @number_of_records <= per_page
      offset_value + @number_of_records
    else
      rel = except(:limit, :offset)
      rel.count(:all)
    end
  end
end
total_pages() click to toggle source
# File lib/smart_paginate/active_record_extension.rb, line 68
def total_pages
  total_entries > 0 ? (total_entries / per_page.to_f).ceil : 1
end

Private Instance Methods

slice_records!() click to toggle source

remember total number of fetched records and slice records to per_page

# File lib/smart_paginate/active_record_extension.rb, line 89
def slice_records!
  @number_of_records ||= @records.length

  if @number_of_records > per_page
    @records = @records.slice(0, per_page)
  end
end