Class: Anchormodel::ActiveModelTypeValueMulti
- Inherits:
-
ActiveModelTypeValueSingle
- Object
- ActiveModel::Type::Value
- ActiveModelTypeValueSingle
- Anchormodel::ActiveModelTypeValueMulti
- 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
Instance Method Summary collapse
-
#cast(values) ⇒ Set<Anchormodel>
Splits the stored CSV and casts each entry into an Anchormodel instance.
-
#serializable?(values) ⇒ Boolean
Reports whether #serialize would accept
values. -
#serialize(values) ⇒ String
Serializes a Set/Array of anchormodel-shaped values into a CSV
Stringfor the DB.
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.
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.
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).
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 |