Created
November 14, 2013 13:37
-
-
Save olly/7466900 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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