Castkit ActiveRecord
Castkit::ActiveRecord is a companion gem to Castkit that bridges your Castkit::DataObject classes with ActiveRecord models. It enables conversion to/from models, assignment, and safe update flows for nested objects.
Installation
bundle add castkit-activerecordUsage
Setup
Include the module in your Castkit::DataObject class and associate it with a model:
class UserDto < Castkit::DataObject
include Castkit::ActiveRecord
model User
string :name
has_many :posts, of: PostDto
endConverting a Model to a DTO
user_dto = UserDto.from_model(User.find(1))Converting a DTO to a Model
user_model = user_dto.to_modelUpdating a Model from a DTO
user.update_from_dataobject(user_dto, mode: :merge)Use update_from_dataobject! if you want to raise on failure. Pass ignore: [:field] to skip certain fields.
Nested Support
Nested dataobject and has_many/has_one relationships are supported:
class PostDto < Castkit::DataObject
include Castkit::ActiveRecord
model Post
string :title
dataobject :author, UserDto
endOpting Out of Attribute Updates
You can skip certain fields from being assigned during updates:
# This is automatically included
class User < ApplicationRecord
castkit_ignored_on_update :id, :status
endUpdate Modes
-
:replace— full object replacement (default) -
:merge— performs recursive merging viaupdate_from_dataobject!on nested models
Methods
On Castkit::DataObject
-
to_model→ Instantiates a model from the DTO
On ActiveRecord::Base
to_dataobject(UserDto)update_from_dataobject(dto, mode: :replace, ignore: [])update_from_dataobject!(dto, mode: :replace, ignore: [])
📃 License
MIT. See LICENSE.
🙏 Credits
Created with ❤️ by Nathan Lucas