Skip to content

Commit 0c068b1

Browse files
committed
Merge pull request #198 from waterlink/fix/176/classes_with_extended_modules_with_contracts
Fix classes that extend modules where contracts were included
2 parents 51cfe7c + e637c44 commit 0c068b1

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

Diff for: lib/contracts/core.rb

+11-2
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,22 @@ def functype(funcname)
2424
end
2525
end
2626

27-
base.class_eval do
27+
# NOTE: Workaround for `defined?(super)` bug in ruby 1.9.2
28+
# source: http://stackoverflow.com/a/11181685
29+
# bug: https://bugs.ruby-lang.org/issues/6644
30+
base.class_eval <<-RUBY
2831
# TODO: deprecate
2932
# Required when contracts are included in global scope
3033
def Contract(*args)
31-
self.class.Contract(*args)
34+
if defined?(super)
35+
super
36+
else
37+
self.class.Contract(*args)
38+
end
3239
end
40+
RUBY
3341

42+
base.class_eval do
3443
def functype(funcname)
3544
contracts = Engine.fetch_from(self.class).decorated_methods_for(:instance_methods, funcname)
3645
if contracts.nil?

Diff for: spec/contracts_spec.rb

+29
Original file line numberDiff line numberDiff line change
@@ -717,4 +717,33 @@ def delim(match)
717717
expect { c.double("asd") }.to raise_error
718718
end
719719
end
720+
721+
describe "classes with extended modules" do
722+
let(:klass) do
723+
m = Module.new do
724+
include Contracts::Core
725+
end
726+
727+
Class.new do
728+
include Contracts::Core
729+
extend m
730+
731+
Contract String => nil
732+
def foo(x)
733+
end
734+
end
735+
end
736+
737+
it "is possible to define it" do
738+
expect { klass }.not_to raise_error
739+
end
740+
741+
it "works correctly with methods with passing contracts" do
742+
expect { klass.new.foo("bar") }.not_to raise_error
743+
end
744+
745+
it "works correctly with methods with passing contracts" do
746+
expect { klass.new.foo(42) }.to raise_error(ContractError, /Expected: String/)
747+
end
748+
end
720749
end

0 commit comments

Comments
 (0)