Skip to content

Instantly share code, notes, and snippets.

@olly
Created November 14, 2013 13:37
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 olly/7466900 to your computer and use it in GitHub Desktop.
Save olly/7466900 to your computer and use it in GitHub Desktop.
class Item
def self.find_each(params = {})
return enum_for(:find_each) unless block_given?
page = nil
while page.nil? || page.current_page < page.total_pages
if page.nil?
page = all params
else
page = all params.merge(page: page.current_page + 1)
end
page.each do |item|
yield item
end
end
end
def self.all(params = {})
# snip
end
end
# yields as it goes, retrieving pages as needed behind the scenes
Item.find_each do |item|
puts item.name
end
# only retrieves the first two pages
# Ruby 1.9 doesn't do lazy map or reduce, I think?
Item.find_each.take(75).map(&:price).reduce(:+)
# only retrieves the first two pages
# Ruby 2 allows this?
Item.find_each.map(&:price).reduce(:+).take(75)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment