Skip to content

Instantly share code, notes, and snippets.

@udit99
Created July 25, 2014 18:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save udit99/569f990b91a06494be38 to your computer and use it in GitHub Desktop.
Save udit99/569f990b91a06494be38 to your computer and use it in GitHub Desktop.
Ruby Co-routines Demo
# 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