Skip to content

Commit de0d944

Browse files
committed
Fix maybe proc
1 parent 3a10339 commit de0d944

File tree

4 files changed

+33
-3
lines changed

4 files changed

+33
-3
lines changed

lib/contracts.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,9 @@ def initialize(klass, method, *contracts)
113113
# == @has_proc_contract
114114
last_contract = args_contracts.last
115115
is_a_proc = last_contract.is_a?(Class) && (last_contract <= Proc || last_contract <= Method)
116+
maybe_a_proc = last_contract.is_a?(Contracts::Maybe) && last_contract.include_proc?
116117

117-
@has_proc_contract = is_a_proc || last_contract.is_a?(Contracts::Func)
118+
@has_proc_contract = is_a_proc || maybe_a_proc || last_contract.is_a?(Contracts::Func)
118119
# ====
119120

120121
# == @has_options_contract

lib/contracts/builtin_contracts.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,10 @@ class Maybe < Or
352352
def initialize(*vals)
353353
super(*(vals + [nil]))
354354
end
355+
356+
def include_proc?
357+
@vals.include? Proc
358+
end
355359
end
356360

357361
# Used to define contracts on functions passed in as arguments.

spec/contracts_spec.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,26 @@ def self.greeting(name)
404404
@o.double_with_proc(4)
405405
end.to raise_error(ContractError, /Actual: nil/)
406406
end
407+
408+
it "should succeed for maybe proc with no proc" do
409+
expect do
410+
@o.maybe_call(5)
411+
end.to_not raise_error
412+
end
413+
414+
it "should succeed for maybe proc with proc" do
415+
expect do
416+
@o.maybe_call(5) do
417+
2 + 2
418+
end
419+
end.to_not raise_error
420+
end
421+
422+
it "should fail for maybe proc with invalid input" do
423+
expect do
424+
@o.maybe_call("bad")
425+
end.to raise_error(ContractError)
426+
end
407427
end
408428

409429
describe "varargs" do

spec/fixtures/fixtures.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,13 @@ def nested_array_complex_contracts(data)
120120
end
121121

122122
Contract Proc => Any
123-
def do_call(&blk)
124-
blk.call
123+
def do_call(&block)
124+
block.call
125+
end
126+
127+
Contract Args[Num], Maybe[Proc] => Any
128+
def maybe_call(*vals, &block)
129+
block.call if block
125130
end
126131

127132
Contract Args[Num] => Num

0 commit comments

Comments
 (0)