Skip to content

Instantly share code, notes, and snippets.

@practicingruby
Created November 16, 2012 03:23
Show Gist options
  • Select an option

  • Save practicingruby/4083744 to your computer and use it in GitHub Desktop.

Select an option

Save practicingruby/4083744 to your computer and use it in GitHub Desktop.
module Contractor
FailedContract = Class.new(StandardError)
class << self
attr_accessor :enabled
end
def precondition(method, &block)
constraint = Module.new do
define_method method do |*a,&b|
return unless Contractor.enabled
raise FailedContract unless instance_exec(*a, b, &block)
super(*a, &b)
end
end
prepend(constraint)
end
def postcondition(method, &block)
constraint = Module.new do
define_method method do |*a,&b|
return unless Contractor.enabled
result = super(*a, &b)
raise FailedContract unless instance_exec(result, &block)
result
end
end
prepend(constraint)
end
end
class IntegerStack
extend Contractor
def initialize
@stack = []
end
precondition(:push) { |obj| obj.kind_of?(Integer) }
postcondition(:push) { |result| result == count }
def push(obj)
@stack << obj
count
end
def count
@stack.count
end
end
Contractor.enabled = true
s = IntegerStack.new
6.times { |i| s.push(i) }
s.push("foo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment