Class: Nylas::Types::ModelType

Inherits:
ValueType show all
Defined in:
lib/nylas/types.rb

Overview

Type for attributes that are persisted in the API as a hash but exposed in ruby as a particular Model or Model-like thing.

Direct Known Subclasses

DeltaType, MessageHeadersType, NylasDateType

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from ValueType

#deseralize

Constructor Details

#initialize(model:) ⇒ ModelType

Returns a new instance of ModelType.



47
48
49
50
# File 'lib/nylas/types.rb', line 47

def initialize(model:)
  super()
  self.model = model
end

Instance Attribute Details

#modelObject

Returns the value of attribute model.



45
46
47
# File 'lib/nylas/types.rb', line 45

def model
  @model
end

Instance Method Details

#actual_attributes(hash) ⇒ Object



72
73
74
75
76
# File 'lib/nylas/types.rb', line 72

def actual_attributes(hash)
  model.attribute_definitions.keys.each_with_object({}) do |attribute_name, attributes|
    attributes[attribute_name] = hash[json_key_from_attribute_name(attribute_name)]
  end
end

#already_cast?(value) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/nylas/types.rb', line 68

def already_cast?(value)
  model.attribute_definitions.keys.all? { |attribute_name| value.respond_to?(attribute_name) }
end

#cast(value) ⇒ Object

Raises:

  • (TypeError)


60
61
62
63
64
65
66
# File 'lib/nylas/types.rb', line 60

def cast(value)
  return model.new if value.nil?
  return value if already_cast?(value)
  return model.new(**actual_attributes(value)) if value.respond_to?(:key?)

  raise TypeError, "Unable to cast #{value} to a #{model}"
end

#json_key_from_attribute_name(name) ⇒ Object



78
79
80
# File 'lib/nylas/types.rb', line 78

def json_key_from_attribute_name(name)
  name
end

#serialize(object) ⇒ Object



52
53
54
# File 'lib/nylas/types.rb', line 52

def serialize(object)
  object.to_h
end

#serialize_for_api(object) ⇒ Object



56
57
58
# File 'lib/nylas/types.rb', line 56

def serialize_for_api(object)
  object&.to_h(enforce_read_only: true)
end