Class: Castkit::ActiveRecord::AttributeAssigner

Inherits:
Object
  • Object
show all
Defined in:
lib/castkit/active_record/attribute_assigner.rb

Overview

Converts a Castkit::DataObject into a hash of assignable attributes for ActiveRecord model instances.

This handles nested ‘dataobject` and `dataobject_collection` types, and supports recursive conversion using `.to_model` or `.update_from_dataobject!`.

Constant Summary collapse

UPDATE_MODES =

Supported update modes

%i[replace merge].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dataobject) ⇒ AttributeAssigner

Returns a new instance of AttributeAssigner.

Parameters:

  • dataobject (Castkit::DataObject)

    the source data object to assign from



28
29
30
31
# File 'lib/castkit/active_record/attribute_assigner.rb', line 28

def initialize(dataobject)
  @dataobject = dataobject
  @attributes = dataobject.class.attributes
end

Class Method Details

.call(dataobject, model = nil, mode: :replace, ignore: []) ⇒ Hash<Symbol, Object>

Builds assignable attributes for a DataObject, suitable for ActiveRecord models.

Parameters:

  • dataobject (Castkit::DataObject)

    the DTO instance

  • model (ActiveRecord::Base, nil) (defaults to: nil)

    optional target model

  • mode (Symbol) (defaults to: :replace)

    the update mode (:replace or :merge)

  • ignore (Array<Symbol>) (defaults to: [])

    additional attribute keys to exclude from assignment

Returns:

  • (Hash<Symbol, Object>)

    model-assignable attributes



22
23
24
# File 'lib/castkit/active_record/attribute_assigner.rb', line 22

def call(dataobject, model = nil, mode: :replace, ignore: [])
  new(dataobject).attributes(model, mode: mode, ignore: ignore)
end

Instance Method Details

#attributes(model = nil, mode: :replace, ignore: []) ⇒ Hash<Symbol, Object>

Returns a filtered and transformed hash of attributes for assignment

Parameters:

  • model (ActiveRecord::Base, nil) (defaults to: nil)

    optional model for filtering

  • mode (Symbol) (defaults to: :replace)

    either :replace or :merge

  • ignore (Array<Symbol>) (defaults to: [])

    optional attribute keys to exclude

Returns:

  • (Hash<Symbol, Object>)

    assignable attributes

Raises:

  • (ArgumentError)

    for invalid mode or assignment failure



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/castkit/active_record/attribute_assigner.rb', line 40

def attributes(model = nil, mode: :replace, ignore: [])
  validate_mode!(mode)

  assignable_attributes(model, ignore).each_with_object({}) do |(field, attribute), hash|
    value = @dataobject.public_send(field)
    (hash[field] = nil) and next unless value

    target = model.public_send(field) if model
    hash[field] = assign(attribute, value, target, mode)
  rescue Castkit::Error
    raise
  rescue StandardError => e
    raise ArgumentError, "Unable to assign attribute #{field}, #{e}"
  end.freeze
end