ContractNum, Num => Num defadd(a, b) a + b end end
p Sample.new.add(0, "number")
実行すると次の通り。
1 2 3 4 5 6 7 8 9 10
$ bundle exec ruby app.rb /usr/local/bundle/gems/contracts-0.17/lib/contracts.rb:51:in `block in <class:Contract>': Contract violation for argument 2 of 2: (ParamContractError) Expected: Num, Actual: "number" Value guarded in: Sample::add With Contract: Num, Num => Num At: app.rb:8 from /usr/local/bundle/gems/contracts-0.17/lib/contracts.rb:197:in `failure_callback' from /usr/local/bundle/gems/contracts-0.17/lib/contracts/method_handler.rb:144:in `block in redefine_method' from app.rb:13:in `<main>'
ContractCustomNum, CustomNum => Num defadd(a, b) a + b end end
p Sample.new.add(0, 1)
実行すると次の通りです。
1 2 3 4 5 6 7 8 9 10
$ bundle exec ruby app.rb /usr/local/bundle/gems/contracts-0.17/lib/contracts.rb:51:in `block in <class:Contract>': Contract violation for argument 1 of 2: (ParamContractError) Expected: CustomNum, Actual: 0 Value guarded in: Sample::add With Contract: CustomNum, CustomNum => Num At: app.rb:15 from /usr/local/bundle/gems/contracts-0.17/lib/contracts.rb:197:in `failure_callback' from /usr/local/bundle/gems/contracts-0.17/lib/contracts/method_handler.rb:144:in `block in redefine_method' from app.rb:20:in `<main>'
classContractError < StandardError definitialize(backtrace, file, line, method, source_code, message) text = "Contract Error!\n" text += "BackTrace: #{backtrace}\n" text += "File: #{file}\n" text += "Line: #{line}\n" text += "Method: #{method}\n" text += "Against the args rules at \`#{source_code}\`\n" text += "Message: #{message}\n"if message