Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define user types that are "hash-like"? #239

Open
mlsquires opened this issue Oct 21, 2016 · 1 comment
Open

Define user types that are "hash-like"? #239

mlsquires opened this issue Oct 21, 2016 · 1 comment

Comments

@mlsquires
Copy link

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?

@egonSchiele
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants