Class: AttrJson::Type::Array

Inherits:
ActiveModel::Type::Value
  • Object
show all
Defined in:
lib/attr_json/type/array.rb

Overview

You can wrap any ActiveModel::Type in one of these, and it's magically a type representing an Array of those things, always returning an array of those things on cast, serialize, and deserialize.

Meant for use with AttrJson::Record and AttrJson::Model, may or may not do something useful or without exceptions in other contexts.

AttrJson::Type::Array.new(base_type)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_type) ⇒ Array

Returns a new instance of Array.



15
16
17
# File 'lib/attr_json/type/array.rb', line 15

def initialize(base_type)
  @base_type = base_type
end

Instance Attribute Details

#base_typeObject (readonly)

Returns the value of attribute base_type.



14
15
16
# File 'lib/attr_json/type/array.rb', line 14

def base_type
  @base_type
end

Instance Method Details

#base_type_primitive?Boolean

Soft-deprecated. You probably want to use

AttrJson::AttributeDefinition#array_of_primitive_type?

instead where possible.

Returns:

  • (Boolean)


55
56
57
# File 'lib/attr_json/type/array.rb', line 55

def base_type_primitive?
  ! AttrJson::AttributeDefinition.single_model_type?(base_type)
end

#cast(value) ⇒ Object



23
24
25
# File 'lib/attr_json/type/array.rb', line 23

def cast(value)
  convert_to_array(value).collect { |v| base_type.cast(v) }
end

#changed_in_place?(raw_old_value, new_value) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/attr_json/type/array.rb', line 35

def changed_in_place?(raw_old_value, new_value)
  serialize(new_value) != raw_old_value
end

#deserialize(value) ⇒ Object



31
32
33
# File 'lib/attr_json/type/array.rb', line 31

def deserialize(value)
  convert_to_array(value).collect { |v| base_type.deserialize(v) }
end

#serialize(value) ⇒ Object



27
28
29
# File 'lib/attr_json/type/array.rb', line 27

def serialize(value)
  convert_to_array(value).collect { |v| base_type.serialize(v) }
end

#typeObject



19
20
21
# File 'lib/attr_json/type/array.rb', line 19

def type
  @type ||= "array_of_#{base_type.type}".to_sym
end

#value_for_contains_query(key_path_arr, value) ⇒ Object

This is used only by our own keypath-chaining query stuff.



40
41
42
43
44
45
46
47
48
# File 'lib/attr_json/type/array.rb', line 40

def value_for_contains_query(key_path_arr, value)
  [
    if key_path_arr.present?
      base_type.value_for_contains_query(key_path_arr, value)
    else
      base_type.serialize(base_type.cast value)
    end
  ]
end