Skip to content

Instantly share code, notes, and snippets.

@david
Created October 10, 2012 08:55
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 david/3864217 to your computer and use it in GitHub Desktop.
Save david/3864217 to your computer and use it in GitHub Desktop.
Outcomes
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
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