Skip to content

Instantly share code, notes, and snippets.

@jvoorhis
Created August 7, 2008 19:57
Show Gist options
  • Save jvoorhis/4481 to your computer and use it in GitHub Desktop.
Save jvoorhis/4481 to your computer and use it in GitHub Desktop.
class PagingModelEnumerator # sketchy version :D
include Enumerable
def initialize(model, opts)
@model = model
@find_opts, @count_opts = parse_opts(opts)
end
def each(&block)
page_size = 50
count = @model.count(@count_opts)
full_pages, incomplete_pages = count.divmod(page_size)
page_count = full_pages + (incomplete_pages.zero? ? 0 : 1)
page_count.times do |page_num|
find_opts = @find_opts.merge :offset => (page_num*page_size), :limit => page_size
@model.find(:all, find_opts).each(&block)
end
end
private
def parse_opts(opts)
if opts.key?(:find) || opts.key?(:count)
[opts.fetch(:find, {}), opts.fetch(:count, {})]
else
[opts, opts]
end
end
end
class ActiveRecord::Base
def self.enumerator(opts = {})
PagingModelEnumerator.new(self, opts)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment