Class: LcpRuby::ModelFactory::ArrayType

Inherits:
ActiveRecord::Type::Value
  • Object
show all
Defined in:
lib/lcp_ruby/model_factory/array_type.rb

Overview

Custom ActiveRecord::Type for array fields on non-PostgreSQL databases. Transparently serializes Ruby Arrays to JSON strings and deserializes back, with item-level type casting based on the configured item_type.

Instance Method Summary collapse

Constructor Details

#initialize(item_type = "string") ⇒ ArrayType

Returns a new instance of ArrayType.



7
8
9
10
# File 'lib/lcp_ruby/model_factory/array_type.rb', line 7

def initialize(item_type = "string")
  @item_type = item_type
  super()
end

Instance Method Details

#cast(value) ⇒ Object

Cast from user input (form params, assignment)



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/lcp_ruby/model_factory/array_type.rb', line 30

def cast(value)
  case value
  when Array then cast_items(value.reject { |v| v.respond_to?(:blank?) && v.blank? })
  when String
    if value.start_with?("[")
      parsed = parse_json_array(value)
      return cast_items(parsed) if parsed
    end
    cast_items(value.split(",").map(&:strip).reject(&:blank?))
  when nil then []
  else [ cast_item(value) ]
  end
end

#changed_in_place?(raw_old_value, new_value) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/lcp_ruby/model_factory/array_type.rb', line 50

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

#deserialize(value) ⇒ Object

Deserialize from DB (JSON string -> Ruby Array)



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/lcp_ruby/model_factory/array_type.rb', line 17

def deserialize(value)
  case value
  when String
    parsed = parse_json_array(value)
    parsed ? cast_items(parsed) : []
  when Array
    cast_items(value)
  else
    []
  end
end

#serialize(value) ⇒ Object

Serialize to DB (Ruby Array -> JSON string)



45
46
47
48
# File 'lib/lcp_ruby/model_factory/array_type.rb', line 45

def serialize(value)
  arr = value.is_a?(Array) ? value : []
  arr.to_json
end

#typeObject



12
13
14
# File 'lib/lcp_ruby/model_factory/array_type.rb', line 12

def type
  :lcp_array
end