Create a gist now

Instantly share code, notes, and snippets.

@jhollinger /fax.rb
Last active Aug 29, 2015

What would you like to do?
Fun with Enumerator
require_relative 'libfax'
puts "Sending fax..."
attempts = mock_fax('555-555-5555', "Here's a fax!")
attempts.each_with_index do |status, i|
case status
when :sent
puts "Fax sent!"
break
when :busy
puts "Line busy!"
if i < 10
sleep 2
next
else
puts "Tried 10 times; aborting."
break
end
else
puts "Error!"
break
end
end
require_relative 'libguess'
puts "Let's plan Infinite Questions!"
turns = guessing_game
turns.each do
print "Guess the word: "
gets.chomp
end
puts "You win!"
puts "Let's play 20 Questions!"
turns = guessing_game
won = turns.each_with_index do |_,i|
break if i+1 > 20
print "Guess the word: "
gets.chomp
end
puts won ? "You won!" : "You lose :("
# Returns an Enumerator in which each iteration will attempt to send the fax. A status is handed to the caller's "each" block, and it decides how to proceed.
# NOTE The domain and API are completely fictitious, but similar enough to some real ones.
def fax(number, body)
Enumerator.new do |y|
# Try (or retry) to send the fax
loop do
# POST the fax to the API
resp = JSON.parse(RestClient.post("https://fax.example.com/api/fax", number: number, body: body))
# Keep polling the status until it's no longer "pending"
status = resp['status'].to_sym
while status == :pending
sleep 2
status = JSON.parse(RestClient.get("https://fax.example.com/api/fax/#{resp['id']}"))['status'].to_sym
end
# Inform the caller of the final status
y << status
end
end
end
# A mock implementation of the fax method. This one will actually run, since it doesn't depend on non-existent APIs.
def mock_fax(number, body)
Enumerator.new do |y|
y << :busy
y << :busy
y << :busy
y << :sent
end
end
def guessing_game
answer = ANSWERS[rand(ANSWERS.size)]
Enumerator.new do |y|
guess = nil
# Keep yielding to the caller for new guess until one matches
until guess == answer
guess = y.yield
end
true
end
end
ANSWERS = %w(
rectangle
america
megaphone
monday
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment