Class: Castkit::DataObject

Inherits:
Object
  • Object
show all
Extended by:
Core::AttributeTypes, Core::Attributes, Core::Config, Core::Registerable, Ext::DataObject::Contract
Includes:
Ext::DataObject::Deserialization, Ext::DataObject::Serialization
Defined in:
lib/castkit/data_object.rb

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::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:



107
108
109
110
111
112
113
114
115
# File 'lib/castkit/data_object.rb', line 107

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.



98
99
100
# File 'lib/castkit/data_object.rb', line 98

def __raw
  @__raw
end

#unknown_attributesHash{Symbol => Object} (readonly)

Returns Undefined attributes provided during instantiation.

Returns:

  • (Hash{Symbol => Object})

    Undefined attributes provided during instantiation.



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

def unknown_attributes
  @unknown_attributes
end

Class Method Details

.build(&block) ⇒ Object



50
51
52
53
54
55
# File 'lib/castkit/data_object.rb', line 50

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:



77
78
79
80
81
82
83
84
85
86
# File 'lib/castkit/data_object.rb', line 77

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)


92
93
94
# File 'lib/castkit/data_object.rb', line 92

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



46
47
48
# File 'lib/castkit/data_object.rb', line 46

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

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

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

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if value does not inherit from Castkit::Serializer



62
63
64
65
66
67
68
69
70
# File 'lib/castkit/data_object.rb', line 62

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

    @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)


121
122
123
# File 'lib/castkit/data_object.rb', line 121

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)


129
130
131
# File 'lib/castkit/data_object.rb', line 129

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