Class: Contracts::Constraints::Tuple

Inherits:
Base
  • Object
show all
Defined in:
lib/contracts/structured.rb

Overview

Matches a fixed-length Array whose positions use independent constraints.

Instance Method Summary collapse

Constructor Details

#initialize(*items) ⇒ Tuple

Returns a new instance of Tuple.



9
10
11
# File 'lib/contracts/structured.rb', line 9

def initialize(*items)
  @items = items.map { |item| Constraints.coerce(item) }.freeze
end

Instance Method Details

#descriptionObject



18
19
20
# File 'lib/contracts/structured.rb', line 18

def description
  "Tuple<#{@items.map(&:description).join(', ')}>"
end

#matches?(value) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
# File 'lib/contracts/structured.rb', line 13

def matches?(value)
  value.is_a?(Array) && value.length == @items.length &&
    @items.each_with_index.all? { |constraint, index| constraint.matches?(value[index]) }
end

#to_hObject



22
23
24
# File 'lib/contracts/structured.rb', line 22

def to_h
  super.merge(items: @items.map(&:description))
end