Sha256: 4af376903088fc4576adc3341b09024066bedb956ed918db10b23f2e8c914ead

Contents?: true

Size: 1.15 KB

Versions: 6

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

class BCDD::Result
  class Contract::ForTypesAndValues
    include Contract::Interface

    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

    def allowed_types
      @types_contract.allowed_types
    end

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

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

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

      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
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
bcdd-result-0.12.0 lib/bcdd/result/contract/for_types_and_values.rb
bcdd-result-0.11.0 lib/bcdd/result/contract/for_types_and_values.rb
bcdd-result-0.10.0 lib/bcdd/result/contract/for_types_and_values.rb
bcdd-result-0.9.1 lib/bcdd/result/contract/for_types_and_values.rb
bcdd-result-0.9.0 lib/bcdd/result/contract/for_types_and_values.rb
bcdd-result-0.8.0 lib/bcdd/result/contract/for_types_and_values.rb