Class: Castkit::DataObject

Overview

Base class for defining declarative, typed data transfer objects (DTOs).

Includes typecasting, validation, access control, serialization, deserialization, and support for custom serializers.

Examples:

Defining a DTO

class UserDto < Castkit::DataObject
  string :name
  integer :age, required: false
end

Instantiating and serializing

user = UserDto.new(name: "Alice", age: 30)
user.to_json #=> '{"name":"Alice","age":30}'

Constant Summary

Constants included from Core::Registerable

Core::Registerable::CASTKIT_NAMESPACES

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Core::Config

allow_unknown, ignore_unknown, relaxed, strict, validation_rules, warn_on_unknown

Methods included from Core::Attributes

attribute, attributes, composite, optional, readonly, required, transient, writeonly

Methods included from Core::AttributeTypes

array, boolean, dataobject, date, datetime, define_type_dsl, float, hash, included, integer, string, unwrapped

Methods included from Core::Registerable

register!

Methods included from Ext::DataObject::Contract

contract, from_contract, to_contract, validate, validate!

Methods included from Ext::DataObject::Plugins

disable_plugins, disabled_plugins, enable_plugins, enabled_plugins, inherited

Methods included from Ext::DataObject::Deserialization

included

Methods included from Ext::DataObject::Serialization

included, #root_key, #root_key_set?

Constructor Details

#initialize(data = {}) ⇒ DataObject

Initializes the DTO from a hash of attributes.

Parameters:

  • data (Hash) (defaults to: {})

    raw input hash

Raises:



111
112
113
114
115
116
117
118
119
# File 'lib/castkit/data_object.rb', line 111

def initialize(data = {})
  @__raw = data.dup.freeze
  data = unwrap_root(data)

  @unknown_attributes = data.reject { |key, _| self.class.attributes.key?(key.to_sym) }.freeze

  validate_data!(data)
  deserialize_attributes!(data)
end

Instance Attribute Details

#__rawHash{Symbol => Object} (readonly)

Returns The raw data provided during instantiation.

Returns:

  • (Hash{Symbol => Object})

    The raw data provided during instantiation.



102
103
104
# File 'lib/castkit/data_object.rb', line 102

def __raw
  @__raw
end

#unknown_attributesHash{Symbol => Object} (readonly)

Returns Undefined attributes provided during instantiation.

Returns:

  • (Hash{Symbol => Object})

    Undefined attributes provided during instantiation.



105
106
107
# File 'lib/castkit/data_object.rb', line 105

def unknown_attributes
  @unknown_attributes
end

Class Method Details

.build(&block) ⇒ Object



52
53
54
55
56
57
# File 'lib/castkit/data_object.rb', line 52

def build(&block)
  klass = Class.new(self)
  klass.class_eval(&block) if block_given?

  klass
end

.cast(obj) ⇒ self

Casts a value into an instance of this class.

Parameters:

  • obj (self, Hash)

Returns:

  • (self)

Raises:



81
82
83
84
85
86
87
88
89
90
# File 'lib/castkit/data_object.rb', line 81

def cast(obj)
  case obj
  when self
    obj
  when Hash
    from_h(obj)
  else
    raise Castkit::DataObjectError, "Can't cast #{obj.class} to #{name}"
  end
end

.dump(obj) ⇒ String

Converts an object to its JSON representation.

Parameters:

Returns:

  • (String)


96
97
98
# File 'lib/castkit/data_object.rb', line 96

def dump(obj)
  obj.to_json
end

.register!(as: nil) ⇒ Class

Registers the current class under ‘Castkit::DataObjects`.

Parameters:

  • as (String, Symbol, nil) (defaults to: nil)

    The constant name to use (PascalCase). Defaults to class name or “Anonymous”.

Returns:

  • (Class)

    the registered dataobject class



48
49
50
# File 'lib/castkit/data_object.rb', line 48

def register!(as: nil)
  super(namespace: :dataobjects, as: as)
end

.serializer(value = nil) ⇒ Class<Castkit::Serializers::Base>?

Gets or sets the serializer class to use for instances of this object.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if value does not inherit from Castkit::Serializers::Base



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/castkit/data_object.rb', line 64

def serializer(value = nil)
  if value
    unless value < Castkit::Serializers::Base
      raise ArgumentError, "Serializer must inherit from Castkit::Serializers::Base"
    end

    @serializer = value
  else
    @serializer
  end
end

Instance Method Details

#to_hash(visited: nil) ⇒ Hash Also known as: to_h, serialize

Serializes the DTO to a Ruby hash.

Parameters:

  • visited (Set, nil) (defaults to: nil)

    used to track circular references

Returns:

  • (Hash)


125
126
127
# File 'lib/castkit/data_object.rb', line 125

def to_hash(visited: nil)
  serializer.call(self, visited: visited)
end

#to_json(options = nil) ⇒ String

Serializes the DTO to a JSON string.

Parameters:

  • options (Hash, nil) (defaults to: nil)

    options passed to ‘JSON.generate`

Returns:

  • (String)


133
134
135
# File 'lib/castkit/data_object.rb', line 133

def to_json(options = nil)
  JSON.generate(serializer.call(self), options)
end