Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save practicingruby/4083717 to your computer and use it in GitHub Desktop.
module Contractor
def precondition(method, &block)
constraint = Module.new do
define_method method do |*a,&b|
raise 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|
result = super(*a, &b)
raise 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
s = IntegerStack.new
6.times { |i| s.push(i) }
@david

david commented Nov 18, 2012

Copy link
Copy Markdown

I'm assuming this fails for default arguments and doesn't work with subclasses. Are there any more instances where it fails? I'm thinking rubinus would probably be the best place to get something like this working.

@david

david commented Nov 18, 2012

Copy link
Copy Markdown

I'm assuming this fails for default arguments and doesn't work with subclasses. Are there any more instances where it fails?

I'm thinking rubinus would probably be the best place to get something like this working.

@david

david commented Nov 18, 2012

Copy link
Copy Markdown

Weird, gist comments aren't showing.

@david

david commented Nov 18, 2012

Copy link
Copy Markdown

Are comments appearing now?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment