contracts.ruby
contracts.ruby copied to clipboard
Define user types that are "hash-like"?
Contracts has "Array" and "ArrayOf". ArrayOf is created using the Contracts::CollectionOf::Factory.new(UserClass) and the class passed in needs to support Array-like operations.
It has "Hash" and "HashOf". It supports a UserClass that is subclassed from Hash (that is, there doesn't appear to be a way to supply an arbitrary user class that provides Hash-like operations.
That is, I want to specify a Contract like: nil => HashOf[String,Integer], but pass in my own user class.
Am I missing a way to do this in today's gem?
You would have to write this yourself. For example:
require "hashie"
require "contracts"
include Contracts
class MashOf
def self.valid? mash
mash.each do |k, v|
return false unless k.is_a?(String) && v.is_a?(Numeric)
end
end
end
Contract MashOf => String
def foo x
"hi"
end
mash = Hashie::Mash.new
mash.age = 30
foo mash # no error
mash.name = "arthur"
foo mash # error, all vals must be numeric