Class: RSchema::Schemas::VariableHash

Inherits:
Object
  • Object
show all
Defined in:
lib/rschema/schemas/variable_hash.rb

Overview

A schema that matches variable-sized ‘Hash` objects, where the keys are not known ahead of time.

Examples:

A hash of integers to strings

schema = RSchema.define { variable_hash(_Integer => _String) }
schema.valid?({ 5 => "hello", 7 => "world" }) #=> true
schema.valid?({}) #=> true

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_schema, value_schema) ⇒ VariableHash

Returns a new instance of VariableHash.



16
17
18
19
# File 'lib/rschema/schemas/variable_hash.rb', line 16

def initialize(key_schema, value_schema)
  @key_schema = key_schema
  @value_schema = value_schema
end

Instance Attribute Details

#key_schemaObject (readonly)

Returns the value of attribute key_schema.



14
15
16
# File 'lib/rschema/schemas/variable_hash.rb', line 14

def key_schema
  @key_schema
end

#value_schemaObject (readonly)

Returns the value of attribute value_schema.



14
15
16
# File 'lib/rschema/schemas/variable_hash.rb', line 14

def value_schema
  @value_schema
end

Instance Method Details

#call(value, options) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rschema/schemas/variable_hash.rb', line 21

def call(value, options)
  return not_a_hash_result(value) unless value.is_a?(Hash)

  result, key_errors, value_errors = apply_subschemas(value, options)

  if key_errors.empty? && value_errors.empty?
    Result.success(result)
  else
    Result.failure(keys: key_errors, values: value_errors)
  end
end

#with_wrapped_subschemas(wrapper) ⇒ Object



33
34
35
36
37
38
# File 'lib/rschema/schemas/variable_hash.rb', line 33

def with_wrapped_subschemas(wrapper)
  self.class.new(
    wrapper.wrap(key_schema),
    wrapper.wrap(value_schema),
  )
end