Skip to content

Instantly share code, notes, and snippets.

@ezekg
Forked from udit99/gist:569f990b91a06494be38
Last active August 29, 2015 14:24
Show Gist options
  • Save ezekg/da7a69b269350a854d3f to your computer and use it in GitHub Desktop.
Save ezekg/da7a69b269350a854d3f to your computer and use it in GitHub Desktop.
# 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