Module: Castkit::ActiveRecord::Extensions
- Defined in:
- lib/castkit/active_record/extensions.rb
Overview
Adds support for customizing update behavior and ergonomic model → DataObject conversion.
When included into an ActiveRecord model, this module allows:
-
Opting out of assigning certain fields during updates via ‘castkit_ignored_on_update`
-
Converting a model instance to a Castkit::DataObject via ‘to_dataobject`
-
Updating a model instance from a Castkit::DataObject via ‘update_from_dataobject!`
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
-
#to_dataobject(klass) ⇒ Castkit::DataObject
Converts this model instance into a Castkit::DataObject.
-
#update_from_dataobject(dto, mode: :replace, ignore: []) ⇒ Boolean
Updates this model instance from a Castkit::DataObject.
-
#update_from_dataobject!(dto, mode: :replace, ignore: []) ⇒ ActiveRecord::Base
Updates this model instance from a Castkit::DataObject.
Class Method Details
.included(base) ⇒ Object
14 15 16 |
# File 'lib/castkit/active_record/extensions.rb', line 14 def self.included(base) base.extend(ClassMethods) end |
Instance Method Details
#to_dataobject(klass) ⇒ Castkit::DataObject
Converts this model instance into a Castkit::DataObject.
56 57 58 59 60 61 62 |
# File 'lib/castkit/active_record/extensions.rb', line 56 def to_dataobject(klass) unless Castkit.dataobject?(klass) && klass.respond_to?(:from_model) raise ArgumentError, "#{klass} must include Castkit::ActiveRecord" end klass.from_model(self) end |
#update_from_dataobject(dto, mode: :replace, ignore: []) ⇒ Boolean
Updates this model instance from a Castkit::DataObject.
This is the safe variant of ‘update_from_dataobject!`, returning false if the update or save fails due to validation errors.
73 74 75 76 77 78 |
# File 'lib/castkit/active_record/extensions.rb', line 73 def update_from_dataobject(dto, mode: :replace, ignore: []) update_from_dataobject!(dto, mode: mode, ignore: ignore) true rescue ::ActiveRecord::RecordInvalid, ::ActiveModel::ValidationError false end |
#update_from_dataobject!(dto, mode: :replace, ignore: []) ⇒ ActiveRecord::Base
Updates this model instance from a Castkit::DataObject.
This performs a recursive update, including nested DataObjects, and saves the model after assignment.
90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/castkit/active_record/extensions.rb', line 90 def update_from_dataobject!(dto, mode: :replace, ignore: []) attributes = Castkit::ActiveRecord::AttributeAssigner.call( dto, self, mode: mode, ignore: ignore ) assign_attributes(attributes) save! self end |