Skip to content

Instantly share code, notes, and snippets.

@ryana
Created May 27, 2011 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryana/996112 to your computer and use it in GitHub Desktop.
Save ryana/996112 to your computer and use it in GitHub Desktop.
mulligan - a concept for dealing with things that can fail frequently
Mulligan.initialize
puts "BEGIN"
#succeeding
mulligan(:times => 4) do
puts "mulligan!"
end.on_failure do
puts "fail"
end.on_success do
puts "winning"
end
#failing
mulligan(:times => 4) do
puts "mulligan!"
raise
end.on_failure do
puts "fail"
end.on_success do
puts "winning"
end
puts "DONE"
module Mulligan
class MulliganResult
attr_accessor :success
def initialize(options)
self.success = options[:success]
end
def on_failure(&block)
if !success
block.call
end
self
end
def on_success(&block)
if success
block.call
end
self
end
end
module InstanceMethods
def mulligan(options, &block)
times_to_run = options.delete(:times) || 1
wait_time = options.delete(:wait_time) || 0.5
times_to_run.times do
begin
block.call
@success = true
break
rescue => e
sleep wait_time
@success = false
end
end
::Mulligan::MulliganResult.new(:success => @success)
end
end
def self.initialize
Object.send(:include, Mulligan::InstanceMethods)
end
end
# A Rails controller action
def update_twitter
mulligan(:times => 4) do
@tweet = current_visitor.twitter_client.update(params[:msg])
end.on_failure do
flash[:error] = 'Could not post tweet'
end.on_success do
Conversation.create! :tweet => @tweet
redirect_to dashboard_path
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment