Class: EntitySchema::Fields::Contracts::Contract

Inherits:
Object
  • Object
show all
Defined in:
lib/entity_schema/fields/contracts/contract.rb

Overview

Check data with strict contract, described with Hash-based DSL

Instance Method Summary collapse

Constructor Details

#initialize(rules) ⇒ Contract

Returns a new instance of Contract.



8
9
10
# File 'lib/entity_schema/fields/contracts/contract.rb', line 8

def initialize(rules)
  @rules = rules
end

Instance Method Details

#+(other) ⇒ Object



12
13
14
# File 'lib/entity_schema/fields/contracts/contract.rb', line 12

def +(other)
  self.class.new(rules.merge(other.to_h))
end

#call(raw_options, skip_unknown: false) ⇒ Object

rubocop:disable Metrics/AbcSize



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/entity_schema/fields/contracts/contract.rb', line 16

def call(raw_options, skip_unknown: false) # rubocop:disable Metrics/AbcSize
  raw_options.each do |key, value|
    rules.key?(key) || skip_unknown || raise_unknown!(key, value)

    r = rules[key]
    next if Array(r[:eq]).any?         { |expectation| expectation == value }
    next if Array(r[:type]).any?       { |type| value.is_a?(type) }
    next if Array(r[:respond_to]).any? { |meth| value.respond_to?(meth) }
    raise_unexpected_value(r, key, value)
  end
  true
end

#to_hObject



29
30
31
# File 'lib/entity_schema/fields/contracts/contract.rb', line 29

def to_h
  rules
end