Skip to content

Instantly share code, notes, and snippets.

@film42
Created October 24, 2015 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save film42/7e846331186a6dd624b7 to your computer and use it in GitHub Desktop.
Save film42/7e846331186a6dd624b7 to your computer and use it in GitHub Desktop.
class AnyPage
attr_reader :sql
def initialize(sql, options = {})
@page_size = options.fetch(:page_size) { 1000 }
@sql = sql
@total_pages = nil
end
def self.page(sql, nth, options = {})
new(sql, options).page(nth)
end
def count
@total_pages ||= begin
statement = <<-SQL
SELECT COUNT(*) FROM (#{sql}) as t
SQL
results = ActiveRecord::Base.connection.execute(statement)
results.first["count"]
end
end
def pages
page_count = count / @page_size
page_count < 1 ? 1 : page_count
end
def page(nth)
nth = nth <= 0 ? 0 : nth - 1
statement = <<-SQL
SELECT * FROM (#{sql}) AS t
LIMIT #{@page_size}
OFFSET #{nth * @page_size}
SQL
ActiveRecord::Base.connection.execute(statement)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment