-
-
Save ezekg/da7a69b269350a854d3f 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
# From top comment on http://www.reddit.com/r/ruby/comments/29hr4x/whats_youre_favorite_ruby_trick_or_quirk_that/?utm_source=rubyweekly&utm_medium=email | |
class FakeRedditApi | |
def initialize | |
@count = 0 | |
end | |
def has_next_post? | |
@count < 20 | |
end | |
def next_post | |
@count+=1 | |
puts "Fetching Post #{@count}" | |
["kitty picture", "karma-whoring repost", "bitcoin circlejerk"].sample | |
end | |
end | |
class RedditApiService | |
def initialize | |
@api = FakeRedditApi.new | |
end | |
#coroutine demo | |
def fetch_posts | |
return to_enum(__callee__) unless block_given? | |
while @api.has_next_post? | |
yield @api.next_post | |
end | |
end | |
end | |
reddit = RedditApiService.new | |
#Will fetch no posts, just return enumerator | |
reddit.fetch_posts | |
#Will fetch 5 posts | |
reddit.fetch_posts.take(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment