contracts.ruby
contracts.ruby copied to clipboard
Allow contracts to be defined on Structs
Item = Struct.new(:name, :weight, :value)
How to specify type constraints on these attributes? Can the contracts library help with this?
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.
example:
Item = Contracts::Struct.new(
name: String,
weight: Num,
value: Money,
) # optional block do ... end here
WDYT?
Ooh yeah that looks great!
Nice. If you're addin that, please also consider value objects (read-only structs). Contracts::Value would be lovely.
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.)