Created
April 20, 2015 15:22
-
-
Save zakky-dev/13dbe504d59066c4b7ff 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 Contract | |
module Contracts | |
def push &contract | |
stack.push contract | |
end | |
def stack | |
@stack || @stack = [] | |
end | |
private :stack | |
end | |
class ContractRequires | |
include Contracts | |
def assert *args | |
stack.each {|r| r.call(*args)} | |
end | |
end | |
class ContractEnsures | |
include Contracts | |
def assert arg | |
stack.each {|e| e.call(arg)} | |
end | |
end | |
class ContractedMethod | |
def initialize &contracts | |
self.instance_eval &contracts | |
end | |
def evaluation *args | |
contract_requires.assert *args | |
ret = @body.call *args | |
contract_ensures.assert ret | |
end | |
def requires &contract | |
contract_requires.push &contract | |
end | |
def ensures &contract | |
contract_ensures.push &contract | |
end | |
def body &method_body | |
@body = method_body | |
end | |
def contract_requires | |
@contract_requires || @contract_requires = ContractRequires.new | |
end | |
def contract_ensures | |
@contract_ensures || @contract_ensures = ContractEnsures.new | |
end | |
protected :requires, :ensures, :body, :contract_requires, :contract_ensures | |
end | |
end | |
m = Contract::ContractedMethod.new do | |
requires do |arg1, arg2| | |
puts "requires" | |
p arg1 | |
p arg2 | |
end | |
ensures do |ret| | |
puts "ensures" | |
p ret | |
end | |
body do |arg1, arg2| | |
puts "body" | |
p arg1 | |
p arg2 | |
"result" | |
end | |
end | |
m.evaluation("first arg", "second arg") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment