-
-
Save practicingruby/4083717 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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) } |
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.
Weird, gist comments aren't showing.
Are comments appearing now?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.