Module: T::Props::CustomType

Extended by:
Helpers, Sig
Includes:
Kernel
Included in:
Enum
Defined in:
lib/types/props/custom_type.rb

Constant Summary

Constants included from Helpers

Helpers::Private

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Sig

sig

Methods included from T::Private::Methods::SingletonMethodHooks

#singleton_method_added

Methods included from T::Private::Methods::MethodHooks

#method_added

Methods included from Helpers

abstract!, final!, interface!, mixes_in_class_methods, requires_ancestor, sealed!

Class Method Details

.checked_serialize(instance) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
# File 'lib/types/props/custom_type.rb', line 102

def self.checked_serialize(instance)
  val = T.cast(instance.class, T::Props::CustomType).serialize(instance)
  unless valid_serialization?(val)
    msg = "#{instance.class} did not serialize to a valid scalar type. It became a: #{val.class}"
    if val.is_a?(Hash)
      msg += "\nIf you want to store a structured Hash, consider using a T::Struct as your type."
    end
    raise TypeError.new(msg)
  end
  val
end

.included(_base) ⇒ Object



54
55
56
57
58
# File 'lib/types/props/custom_type.rb', line 54

def self.included(_base)
  super

  raise 'Please use "extend", not "include" to attach this module'
end

.scalar_type?(val) ⇒ Boolean

Returns:



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/types/props/custom_type.rb', line 61

def self.scalar_type?(val)
  # We don't need to check for val's included modules in
  # T::Configuration.scalar_types, because T::Configuration.scalar_types
  # are all classes.
  #
  # `name` rather than `to_s`: identical for real classes, but returns the
  # cached frozen string (Ruby 3.2+) where to_s allocates per call.
  # Anonymous classes yield nil, and `include?(nil)` is false (an
  # anonymous class can never be a registered scalar type).
  scalar_types = T::Configuration.scalar_types
  klass = val.class
  until klass.nil?
    return true if scalar_types.include?(klass.name)
    klass = klass.superclass
  end
  false
end

.valid_serialization?(val) ⇒ Boolean

Returns:



84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/types/props/custom_type.rb', line 84

def self.valid_serialization?(val)
  case val
  when Array
    val.each do |v|
      return false unless scalar_type?(v)
    end

    true
  else
    scalar_type?(val)
  end
end

Instance Method Details

#deserialize(scalar) ⇒ Object



51
# File 'lib/types/props/custom_type.rb', line 51

def deserialize(scalar); end

#instance?(value) ⇒ Boolean

Returns:



21
22
23
# File 'lib/types/props/custom_type.rb', line 21

def instance?(value)
  self.===(value)
end

#serialize(instance) ⇒ Object



43
# File 'lib/types/props/custom_type.rb', line 43

def serialize(instance); end

#valid?(value) ⇒ Boolean

Returns:



33
34
35
# File 'lib/types/props/custom_type.rb', line 33

def valid?(value)
  instance?(value)
end