Module: Castkit::ActiveRecord

Defined in:
lib/castkit/active_record.rb,
lib/castkit/active_record/error.rb,
lib/castkit/active_record/version.rb,
lib/castkit/active_record/extensions.rb,
lib/castkit/active_record/serialization.rb,
lib/castkit/active_record/attribute_assigner.rb

Overview

Adds ActiveRecord integration to a Castkit::DataObject.

Includes support for defining a corresponding model class, converting models to/from DataObjects, and assigning model attributes.

Examples:

Defining a DataObject for an ActiveRecord model

class UserDto < Castkit::DataObject
  include Castkit::ActiveRecord
  model User

  string :name
  has_many :posts, of: PostDto
end

Defined Under Namespace

Modules: ClassMethods, Extensions, Serialization Classes: AttributeAssigner, Error, InvalidModel, ModelNotDefined

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Called when the module is included in a class.

Extends the class with ActiveRecord-aware relationship DSLs.

Parameters:

  • base (Class)

    the including class



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

def self.included(base)
  base.extend(ClassMethods)

  class << base
    alias_method :belongs_to, :dataobject
    alias_method :has_one,    :dataobject
    alias_method :has_many,   :array
  end
end

Instance Method Details

#to_modelActiveRecord::Base

Builds a new instance of the associated ActiveRecord model from the DataObject’s current values.

Calls ‘to_model` on any nested DataObjects if available.

Returns:

  • (ActiveRecord::Base)

    a new model with attributes assigned

Raises:



79
80
81
82
83
84
85
86
# File 'lib/castkit/active_record.rb', line 79

def to_model
  self.class.ensure_model_defined!
  attributes = Castkit::ActiveRecord::AttributeAssigner.call(self)

  model = self.class.model.new
  model.assign_attributes(attributes)
  model
end