Skip to content

Commit

Permalink
Merge pull request #145 from robnormal/bug_143-contracts-on-returned-…
Browse files Browse the repository at this point in the history
…lambdas

honor Func contract on returns (fixes issue #143)
  • Loading branch information
waterlink committed May 8, 2015
2 parents cf1e9e0 + 3a98600 commit bc4dcd6
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/contracts.rb
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,10 @@ def call_with(this, *args, &blk)

this.verify_invariants!(method) if this.respond_to?(:verify_invariants!)

if ret_contract.is_a?(Contracts::Func)
result = Contract.new(klass, result, *ret_contract.contracts)
end

result
end

Expand Down
12 changes: 12 additions & 0 deletions spec/contracts_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,18 @@ def self.greeting(name)
it "should fail for a function that doesn't pass the contract with weak other args" do
expect { @o.map_plain(["hello", "joe"], lambda { |_| nil }) }.to raise_error(ContractError)
end

it "should fail for a returned function that doesn't pass the contract" do
expect { @o.lambda_with_wrong_return.call("hello") }.to raise_error(ContractError)
end

it "should fail for a returned function that receives the wrong argument type" do
expect { @o.lambda_with_correct_return.call(123) }.to raise_error(ContractError)
end

it "should not fail for a returned function that passes the contract" do
expect { @o.lambda_with_correct_return.call("hello") }.to_not raise_error
end
end

describe "default args to functions" do
Expand Down
10 changes: 10 additions & 0 deletions spec/fixtures/fixtures.rb
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,16 @@ def map_plain(arr, func)
end
end

Contract None => Func[String => Num]
def lambda_with_wrong_return
lambda { |x| x }
end

Contract None => Func[String => Num]
def lambda_with_correct_return
lambda { |x| x.length }
end

Contract Num => Num
def default_args(x = 1)
2
Expand Down

0 comments on commit bc4dcd6

Please sign in to comment.