Class: Castkit::ActiveRecord::AttributeAssigner
- Inherits:
-
Object
- Object
- Castkit::ActiveRecord::AttributeAssigner
- 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
-
.call(dataobject, model = nil, mode: :replace, ignore: []) ⇒ Hash<Symbol, Object>
Builds assignable attributes for a DataObject, suitable for ActiveRecord models.
Instance Method Summary collapse
-
#attributes(model = nil, mode: :replace, ignore: []) ⇒ Hash<Symbol, Object>
Returns a filtered and transformed hash of attributes for assignment.
-
#initialize(dataobject) ⇒ AttributeAssigner
constructor
A new instance of AttributeAssigner.
Constructor Details
#initialize(dataobject) ⇒ AttributeAssigner
Returns a new instance of AttributeAssigner.
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.
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
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 |