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

Define user types that are "hash-like"?

Open mlsquires opened this issue 8 years ago • 1 comments

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?

mlsquires avatar Oct 21 '16 03:10 mlsquires

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

egonSchiele avatar Jan 17 '17 22:01 egonSchiele