contracts.ruby icon indicating copy to clipboard operation
contracts.ruby copied to clipboard

Override only Contracts

Open zerongjiang opened this issue 9 years ago • 2 comments

Is that possible to make this work?

Only override the contract for the override method,

class Super
  include Contracts

  Contract Num => Any
  def initialize(arg)
    puts arg
  end
end

class Sub < Super
  Contract String => Any
  def initialize(arg)
    super
  end
end

Super.new(11) 
Sub.new(11)        #Contract Violation:  Expected: String
Sub.new('hello')  # Contract Violation:  Expected: Num

Thanks!

zerongjiang avatar Jan 15 '16 21:01 zerongjiang

If you examine the a rough callstack of Sub.new(11) call:

- `main`
- `Contract String => Any - validator`
- `Sub.initialize`
- `super`
- `Contract Num => Any - validator`
- `Super.initialize`

I don't think it is possible at the moment. For that to be possible. It looks like there should be a way to unregister the contract for the current class. Even then, I don't think it would be easy to implement. Not saying that it will be weird in the user code..

waterlink avatar Jan 16 '16 20:01 waterlink

Another thing is to try making some helper, like contracts_super for usage instead of super. But that will change your code too much (you will have to provide all arguments to contracts_super at any point of time). And it will be way confusing for any new to the codebase..

waterlink avatar Jan 16 '16 20:01 waterlink