Class: Explicit::Type::Hash

Inherits:
Explicit::Type show all
Defined in:
lib/explicit/type/hash.rb

Instance Attribute Summary collapse

Attributes inherited from Explicit::Type

#auth_type, #default, #description, #nilable, #param_location

Instance Method Summary collapse

Methods inherited from Explicit::Type

#auth_basic?, #auth_bearer?, build, #error_i18n, #mcp_schema, #merge_base_json_schema, #param_location_body?, #param_location_path?, #param_location_query?, #required?, #swagger_i18n, #swagger_schema

Constructor Details

#initialize(key_type:, value_type:, empty: true) ⇒ Hash

Returns a new instance of Hash.



6
7
8
9
10
# File 'lib/explicit/type/hash.rb', line 6

def initialize(key_type:, value_type:, empty: true)
  @key_type = Explicit::Type.build(key_type)
  @value_type = Explicit::Type.build(value_type)
  @empty = empty
end

Instance Attribute Details

#emptyObject (readonly)

Returns the value of attribute empty.



4
5
6
# File 'lib/explicit/type/hash.rb', line 4

def empty
  @empty
end

#key_typeObject (readonly)

Returns the value of attribute key_type.



4
5
6
# File 'lib/explicit/type/hash.rb', line 4

def key_type
  @key_type
end

#value_typeObject (readonly)

Returns the value of attribute value_type.



4
5
6
# File 'lib/explicit/type/hash.rb', line 4

def value_type
  @value_type
end

Instance Method Details

#json_schema(flavour) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/explicit/type/hash.rb', line 49

def json_schema(flavour)
  {
    type: "object",
    additionalProperties: value_type.mcp_schema,
    description_topics: [
      empty == false ? swagger_i18n("hash_not_empty") : nil
    ]
  }
end

#validate(value) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/explicit/type/hash.rb', line 12

def validate(value)
  if !value.respond_to?(:[]) || value.is_a?(::String) || value.is_a?(::Array)
    return error_i18n("hash")
  end

  return error_i18n("empty") if value.empty? && empty == false

  validated_hash = {}

  value.each do |key, value|
    case [key_type.validate(key), value_type.validate(value)]
    in [[:ok, validated_key], [:ok, validated_value]]
      validated_hash[validated_key] = validated_value
    in [[:error, error], _]
      return error_i18n("hash_key", key:, error:)
    in [_, [:error, error]]
      return error_i18n("hash_value", key:, error:)
    end
  end

  [:ok, validated_hash]
end