Class: CouchbaseOrm::Types::Nested

Inherits:
ActiveModel::Type::Value
  • Object
show all
Defined in:
lib/couchbase-orm/types/nested.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type:) ⇒ Nested

Returns a new instance of Nested.

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
# File 'lib/couchbase-orm/types/nested.rb', line 18

def initialize(type:)
    raise ArgumentError, "type is nil" if type.nil?
    raise ArgumentError, "type is not a class : #{type.inspect}" unless type.is_a?(Class)
    
    @model_class = type
    super()
end

Instance Attribute Details

#model_classObject (readonly)

Returns the value of attribute model_class.



16
17
18
# File 'lib/couchbase-orm/types/nested.rb', line 16

def model_class
  @model_class
end

Instance Method Details

#cast(value) ⇒ Object

Raises:

  • (ArgumentError)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/couchbase-orm/types/nested.rb', line 26

def cast(value)
    return nil if value.nil?
    return value if value.is_a?(@model_class)

    if value.is_a?(Hash)
        # Filter out ignored properties before creating the nested instance
        # Optimization: only call .except if there are properties to ignore
        ignored = @model_class.ignored_properties
        filtered_value = ignored.empty? ? value : value.except(*ignored)
        return @model_class.new(filtered_value)
    end

    raise ArgumentError, "Nested: #{value.inspect} (#{value.class}) is not supported for cast"
end

#serialize(value) ⇒ Object

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/couchbase-orm/types/nested.rb', line 41

def serialize(value)
    return nil if value.nil?

    if value.is_a?(Hash)
        # Filter out ignored properties before creating the nested instance
        # Optimization: only call .except if there are properties to ignore
        ignored = @model_class.ignored_properties
        filtered_value = ignored.empty? ? value : value.except(*ignored)
        value = @model_class.new(filtered_value)
    end

    return value.send(:serialized_attributes) if value.is_a?(@model_class)

    raise ArgumentError, "Nested: #{value.inspect} (#{value.class}) is not supported for serialization"
end