Class: Restspec::Schema::Types::HashType

Inherits:
BasicType
  • Object
show all
Defined in:
lib/restspec/schema/types/hash_type.rb

Overview

It represent embedded hashes, but not schematic ones. For them use the EmbeddedSchemaType.

This Hash can receive the following options:

  • schema_options:
    • value_type: A type specifying the type of the values of the hash.
    • keys: What are the keys that should be present in the hash.

Instance Method Summary collapse

Methods inherited from BasicType

#initialize, #of, #to_s, #totally_valid?, #|

Constructor Details

This class inherits a constructor from Restspec::Schema::Types::BasicType

Instance Method Details

#example_for(attribute) ⇒ Hash

Generates an empty hash for a example. It could be better soon.

Parameters:

Returns:

  • (Hash)

    An empty Hash.



17
18
19
# File 'lib/restspec/schema/types/hash_type.rb', line 17

def example_for(attribute)
  {}
end

#valid?(attribute, value) ⇒ true, false

Checks if the object is a valid hash with the specified keys if they are specified or the specified value type.

Examples:

HashType.new.valid?(attribute, { a: 1 })
# => true
HashType.new(schema_options: { keys: ['age', 'name'] }).valid?(attribute, { a: 1 })
# =>  false
HashType.new(schema_options: { keys: ['age', 'name'] }).valid?(attribute, { age: 1, name: 'John' })
# =>  true
HashType.new(schema_options: { value_type: StringType.new }).valid?(attribute, { a: 1 })
# =>  false
HashType.new(schema_options: { value_type: StringType.new }).valid?(attribute, { a: "1" })
# =>  true

Parameters:

Returns:

  • (true, false)

    If the value is a correct Hash.



40
41
42
# File 'lib/restspec/schema/types/hash_type.rb', line 40

def valid?(attribute, value)
  value.is_a?(Hash) && valid_keys?(value) && valid_value_types?(attribute, value)
end