Skip to content

Fix classes that extend modules where contracts were included #198

New issue

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

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

Already on GitHub? # to your account

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
13 changes: 11 additions & 2 deletions lib/contracts/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,22 @@ def functype(funcname)
end
end

base.class_eval do
# NOTE: Workaround for `defined?(super)` bug in ruby 1.9.2
# source: http://stackoverflow.com/a/11181685
# bug: https://bugs.ruby-lang.org/issues/6644
base.class_eval <<-RUBY
# TODO: deprecate
# Required when contracts are included in global scope
def Contract(*args)
self.class.Contract(*args)
if defined?(super)
super
else
self.class.Contract(*args)
end
end
RUBY

base.class_eval do
def functype(funcname)
contracts = Engine.fetch_from(self.class).decorated_methods_for(:instance_methods, funcname)
if contracts.nil?
Expand Down
29 changes: 29 additions & 0 deletions spec/contracts_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -717,4 +717,33 @@ def delim(match)
expect { c.double("asd") }.to raise_error
end
end

describe "classes with extended modules" do
let(:klass) do
m = Module.new do
include Contracts::Core
end

Class.new do
include Contracts::Core
extend m

Contract String => nil
def foo(x)
end
end
end

it "is possible to define it" do
expect { klass }.not_to raise_error
end

it "works correctly with methods with passing contracts" do
expect { klass.new.foo("bar") }.not_to raise_error
end

it "works correctly with methods with passing contracts" do
expect { klass.new.foo(42) }.to raise_error(ContractError, /Expected: String/)
end
end
end