Class: Anchormodel::ActiveModelTypeValueMulti

Inherits:
ActiveModelTypeValueSingle show all
Defined in:
lib/anchormodel/active_model_type_value_multi.rb

Overview

ActiveModel type adapter for collection-valued anchormodel attributes (belongs_to_anchormodels).

Translates between an in-memory Set<Anchormodel> and a CSV String stored in a single DB column. Inherits scalar handling from ActiveModelTypeValueSingle and overrides the collection-aware methods.

Instance Attribute Summary

Attributes inherited from ActiveModelTypeValueSingle

#attribute

Instance Method Summary collapse

Methods inherited from ActiveModelTypeValueSingle

#changed_in_place?, #initialize, #type

Constructor Details

This class inherits a constructor from Anchormodel::ActiveModelTypeValueSingle

Instance Method Details

#cast(values) ⇒ Set<Anchormodel>

Splits the stored CSV and casts each entry into an Anchormodel instance.

Parameters:

  • values (String, nil)

    CSV string from the DB, or nil (NULL).

Returns:

  • (Set<Anchormodel>)

    Set of Anchormodel instances. Empty when values is nil or "".

Raises:



14
15
16
17
# File 'lib/anchormodel/active_model_type_value_multi.rb', line 14

def cast(values)
  return Set.new if values.nil?
  return values.split(',').map { |value| super(value) }.compact.to_set
end

#serializable?(values) ⇒ Boolean

Reports whether #serialize would accept values. Returns strict Boolean.

Parameters:

  • values (Object)

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/anchormodel/active_model_type_value_multi.rb', line 45

def serializable?(values)
  return case values
         when Enumerable
           values.all? { |value| super(value) }
         when String
           values.split(',').all? { |value| super(value) }
         when nil
           true
         else
           false
         end
end

#serialize(values) ⇒ String

Serializes a Set/Array of anchormodel-shaped values into a CSV String for the DB. Validates every entry and raises immediately on invalid keys (rather than deferring the error to the next read).

Parameters:

  • values (Enumerable, String, nil)

    Collection of anchormodel-shaped values, a pre-formed CSV String, or nil.

Returns:

  • (String)

    CSV of validated keys, or "" for nil / empty collection.

Raises:

  • (Anchormodel::InvalidKey)

    if any element is an unknown key.

  • (RuntimeError)

    if values is not an Enumerable, String, or nil.



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/anchormodel/active_model_type_value_multi.rb', line 28

def serialize(values)
  return case values
         when Enumerable
           values.map { |value| super(value) }.compact.join(',')
         when String
           values.split(',').map { |value| super(value) }.compact.join(',')
         when nil
           ''
         else
           fail "Attempt to set #{@attribute.attribute_name} to unsupported type #{values.class}"
         end
end