Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix maybe proc #142

Merged
merged 1 commit into from
Apr 29, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Fix maybe proc
  • Loading branch information
sfcgeorge committed Apr 28, 2015
commit de0d944fe6cb3ee7dab78ac5a811777f2c0c97c5
3 changes: 2 additions & 1 deletion lib/contracts.rb
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,9 @@ def initialize(klass, method, *contracts)
# == @has_proc_contract
last_contract = args_contracts.last
is_a_proc = last_contract.is_a?(Class) && (last_contract <= Proc || last_contract <= Method)
maybe_a_proc = last_contract.is_a?(Contracts::Maybe) && last_contract.include_proc?

@has_proc_contract = is_a_proc || last_contract.is_a?(Contracts::Func)
@has_proc_contract = is_a_proc || maybe_a_proc || last_contract.is_a?(Contracts::Func)
# ====

# == @has_options_contract
Expand Down
4 changes: 4 additions & 0 deletions lib/contracts/builtin_contracts.rb
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,10 @@ class Maybe < Or
def initialize(*vals)
super(*(vals + [nil]))
end

def include_proc?
@vals.include? Proc
end
end

# Used to define contracts on functions passed in as arguments.
Expand Down
20 changes: 20 additions & 0 deletions spec/contracts_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,26 @@ def self.greeting(name)
@o.double_with_proc(4)
end.to raise_error(ContractError, /Actual: nil/)
end

it "should succeed for maybe proc with no proc" do
expect do
@o.maybe_call(5)
end.to_not raise_error
end

it "should succeed for maybe proc with proc" do
expect do
@o.maybe_call(5) do
2 + 2
end
end.to_not raise_error
end

it "should fail for maybe proc with invalid input" do
expect do
@o.maybe_call("bad")
end.to raise_error(ContractError)
end
end

describe "varargs" do
Expand Down
9 changes: 7 additions & 2 deletions spec/fixtures/fixtures.rb
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,13 @@ def nested_array_complex_contracts(data)
end

Contract Proc => Any
def do_call(&blk)
blk.call
def do_call(&block)
block.call
end

Contract Args[Num], Maybe[Proc] => Any
def maybe_call(*vals, &block)
block.call if block
end

Contract Args[Num] => Num
Expand Down