Created
October 10, 2012 08:55
-
-
Save david/3864217 to your computer and use it in GitHub Desktop.
Outcomes
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
class Outcome | |
HANDLER = "if_" | |
HANDLER_RX = /^#{HANDLER}/ | |
QUERY_RX = /\?$/ | |
def self.new(result, *args, &b) | |
super.tap { |o| yield o if block_given? } | |
end | |
def initialize(result, *args) | |
@result = result.to_s | |
@args = args | |
end | |
def announce(listener) | |
listener.send(@result, *@args) | |
self | |
end | |
def method_missing(name, *args) | |
super if not args.empty? | |
case n = name.to_s | |
when result_handler then yield(*args); self | |
when HANDLER_RX then self | |
when QUERY_RX then @result == n.sub(QUERY_RX, '') | |
else super | |
end | |
end | |
private | |
def result_handler | |
"#{HANDLER}#{@result}" | |
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
require 'spec_helper' | |
describe Outcome do | |
subject(:outcome) { Outcome.new(:done) } | |
it "yields if passed a block" do | |
expect { |b| Outcome.new(:done, &b) }.to yield_control | |
end | |
it "answers what the outcome was " do | |
expect(outcome).to be_done | |
end | |
it "announces the outcome" do | |
mock(self).done | |
outcome.announce(self) | |
end | |
it "executes a code block if it corresponds to the outcome" do | |
expect { |b| outcome.if_done(&b) }.to yield_control | |
end | |
it "does not execute a code block if it doesn't correspond to the outcome" do | |
expect { |b| outcome.if_jack(&b) }.not_to yield_control | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment