Class: JsonModel::TypeSpec::Castable

Inherits:
JsonModel::TypeSpec show all
Defined in:
lib/json_model/type_spec/castable.rb

Constant Summary

Constants inherited from JsonModel::TypeSpec

TYPE_MAP

Instance Method Summary collapse

Methods inherited from JsonModel::TypeSpec

#referenced_schemas, #register_validations, resolve

Constructor Details

#initialize(format:, &cast_block) ⇒ Castable

Returns a new instance of Castable.

Parameters:

  • format (String)
  • cast_block (Proc)


8
9
10
11
12
# File 'lib/json_model/type_spec/castable.rb', line 8

def initialize(format:, &cast_block)
  super()
  @format = format
  @cast_block = cast_block
end

Instance Method Details

#as_schema(**_options) ⇒ Hash

Parameters:

  • _options (Hash)

Returns:

  • (Hash)


16
17
18
19
20
21
# File 'lib/json_model/type_spec/castable.rb', line 16

def as_schema(**_options)
  {
    type: 'string',
    format: @format,
  }
end

#cast(json) ⇒ ::Object?

Parameters:

  • json (::Object)

Returns:

  • (::Object, nil)


25
26
27
28
29
30
31
# File 'lib/json_model/type_spec/castable.rb', line 25

def cast(json)
  if json.nil?
    nil
  else
    @cast_block.call(json)
  end
end