Created
May 27, 2011 20:33
-
-
Save ryana/996112 to your computer and use it in GitHub Desktop.
mulligan - a concept for dealing with things that can fail frequently
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
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" |
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
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 |
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
# 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