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

Allow contracts to be defined on Structs

Open egonSchiele opened this issue 9 years ago • 6 comments

Item = Struct.new(:name, :weight, :value)

How to specify type constraints on these attributes? Can the contracts library help with this?

egonSchiele avatar Mar 22 '15 19:03 egonSchiele

Currently it can be like this:

Item = Struct.new(:name, :weight, :value) do
  include Contracts

  Contract String, Num, Maybe[Num] => None
  def initialize(*args)
    super
    nil
  end
end

Shortcut would be nice.

waterlink avatar Mar 22 '15 22:03 waterlink

example:

Item = Contracts::Struct.new(
  name: String,
  weight: Num,
  value: Money,
) # optional block do ... end here 

alex-fedorov avatar Apr 28 '15 15:04 alex-fedorov

WDYT?

alex-fedorov avatar Apr 28 '15 15:04 alex-fedorov

Ooh yeah that looks great!

egonSchiele avatar Apr 28 '15 15:04 egonSchiele

Nice. If you're addin that, please also consider value objects (read-only structs). Contracts::Value would be lovely.

gsinclair avatar Jun 16 '15 21:06 gsinclair

I created a contracts-enabled value object for my own use.

Person = GS::Value.new(name: String, age: Nat, married: Bool)
                  .default(married: false)
                  .create

p = Person.new(name: 'John', age: 37)
# etc... many more features

See https://github.com/gsinclair/gsrubylib

Happy for any of that code to be used in Contracts if desired.

(Edited to correct: my value objects are "contracts-enabled" but they use ArgumentError to signal errors rather than ContractError.)

gsinclair avatar Jun 27 '15 11:06 gsinclair