Class: Contracts::CollectionOf

Inherits:
CallableClass show all
Defined in:
lib/contracts/builtin_contracts.rb

Overview

Takes a collection(responds to :each) type and a contract. The related argument must be of specified collection type. Checks the contract against every element of the collection. If it passes for all elements, the contract passes. Example: CollectionOf[Array, Num]

Defined Under Namespace

Classes: Factory

Instance Method Summary collapse

Methods inherited from CallableClass

[]

Constructor Details

#initialize(collection_class, contract) ⇒ CollectionOf

Returns a new instance of CollectionOf.


248
249
250
251
# File 'lib/contracts/builtin_contracts.rb', line 248

def initialize(collection_class, contract)
  @collection_class = collection_class
  @contract = contract
end

Instance Method Details

#to_sObject


261
262
263
# File 'lib/contracts/builtin_contracts.rb', line 261

def to_s
  "a collection #{@collection_class} of #{@contract}"
end

#valid?(vals) ⇒ Boolean

Returns:

  • (Boolean)

253
254
255
256
257
258
259
# File 'lib/contracts/builtin_contracts.rb', line 253

def valid?(vals)
  return false unless vals.is_a?(@collection_class)
  vals.all? do |val|
    res, _ = Contract.valid?(val, @contract)
    res
  end
end