-
-
Save practicingruby/4083744 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 | |
| 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