Module: Castkit::ActiveRecord::Serialization

Included in:
ClassMethods
Defined in:
lib/castkit/active_record/serialization.rb

Overview

Provides methods for serializing and deserializing between ActiveRecord model instances and Castkit::DataObject instances.

This module supports nested associations and optional eager loading for relations.

Instance Method Summary collapse

Instance Method Details

#from_model(obj) ⇒ Castkit::DataObject

Builds a Castkit::DataObject from an ActiveRecord model instance.

Parameters:

  • obj (ActiveRecord::Base)

    the model instance to convert

Returns:

  • (Castkit::DataObject)

    the hydrated DataObject

Raises:



17
18
19
20
# File 'lib/castkit/active_record/serialization.rb', line 17

def from_model(obj)
  ensure_model_type!(obj)
  from_hash(attributes_from_model(obj))
end

#from_relation(relation, eager_load: false, as: nil) ⇒ Array<Castkit::DataObject>

Builds a collection of DataObjects from an ActiveRecord::Relation or array of model instances.

Optionally eager loads nested associations.

Parameters:

  • relation (Enumerable)

    the model collection

  • eager_load (Boolean) (defaults to: false)

    whether to eager load nested associations

  • as (Class<Castkit::DataObject>, nil) (defaults to: nil)

    an optional DataObject class to use

Returns:

  • (Array<Castkit::DataObject>)

    an array of hydrated DataObjects

Raises:

  • (ArgumentError)

    if the relation is not enumerable



31
32
33
34
35
36
37
# File 'lib/castkit/active_record/serialization.rb', line 31

def from_relation(relation, eager_load: false, as: nil)
  dataobject = as || self
  raise ArgumentError, "Expected an Enumerable (e.g. ActiveRecord::Relation)" unless relation.respond_to?(:map)

  relation = relation.includes(*dataobject.nested_associations) if eager_load && relation.respond_to?(:includes)
  relation.map { |record| from_model(record) }
end

#nested_associationsArray<Symbol>

Returns a list of nested association fields defined on the DataObject.

This is used to support eager loading.

Returns:

  • (Array<Symbol>)

    an array of nested field names



44
45
46
# File 'lib/castkit/active_record/serialization.rb', line 44

def nested_associations
  attributes.values.select(&:dataobject?).map(&:field)
end