Class: Solid::Result::Contract::ForTypesAndValues

Inherits:
Object
  • Object
show all
Includes:
Interface
Defined in:
lib/solid/result/contract/for_types_and_values.rb

Instance Method Summary collapse

Constructor Details

#initialize(types_and_values, config) ⇒ ForTypesAndValues

Returns a new instance of ForTypesAndValues.



7
8
9
10
11
12
13
14
15
16
# File 'lib/solid/result/contract/for_types_and_values.rb', line 7

def initialize(types_and_values, config)
  @nil_as_valid_value_checking =
    Config::Options
      .with_defaults(config, :pattern_matching)
      .fetch(:nil_as_valid_value_checking)

  @types_and_values = types_and_values.transform_keys(&:to_sym)

  @types_contract = Contract::ForTypes.new(@types_and_values.keys)
end

Instance Method Details

#allowed_typesObject



18
19
20
# File 'lib/solid/result/contract/for_types_and_values.rb', line 18

def allowed_types
  @types_contract.allowed_types
end

#type!(type) ⇒ Object



26
27
28
# File 'lib/solid/result/contract/for_types_and_values.rb', line 26

def type!(type)
  @types_contract.type!(type)
end

#type?(type) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/solid/result/contract/for_types_and_values.rb', line 22

def type?(type)
  @types_contract.type?(type)
end

#type_and_value!(data) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/solid/result/contract/for_types_and_values.rb', line 30

def type_and_value!(data)
  type, value = data.type, data.value

  return value if IgnoredTypes.include?(type)

  value_checking = @types_and_values[type!(type)]

  checking_result = value_checking === value

  return value if checking_result || (checking_result.nil? && @nil_as_valid_value_checking)

  raise Contract::Error::UnexpectedValue.build(type: type, value: value)
rescue ::NoMatchingPatternError => e
  raise Contract::Error::UnexpectedValue.build(type: data.type, value: data.value, cause: e)
end