Class: ArrayDecimalSerializer

Inherits:
Object
  • Object
show all
Defined in:
app/serializers/array_decimal_serializer.rb

Overview

Note:

Only use this with a json or jsonb back end column.

Serializes arrays of decimal values for storage in a JSON/JSONB column,
coercing every element (including nested arrays) to BigDecimal.

Class Method Summary collapse

Class Method Details

.array_of_decimals(array) ⇒ Array<BigDecimal>+

Recursively coerces every element of the array to BigDecimal.

Parameters:

  • array (Array)

    values to coerce

Returns:

  • (Array<BigDecimal>, Array<Array<BigDecimal>>)

    the coerced array



28
29
30
31
32
33
34
35
36
# File 'app/serializers/array_decimal_serializer.rb', line 28

def self.array_of_decimals(array)
  array.map do |v|
    if v.is_a?(Array)
      array_of_decimals(v)
    else
      v.to_d
    end
  end
end

.dump(array) ⇒ Array<BigDecimal>+

Prepares an array for database storage.

Parameters:

  • array (Array, nil)

    values to coerce to decimals

Returns:

  • (Array<BigDecimal>, Array<Array<BigDecimal>>)

    the coerced array



12
13
14
# File 'app/serializers/array_decimal_serializer.rb', line 12

def self.dump(array)
  array_of_decimals(array || [])
end

.load(array) ⇒ Array<BigDecimal>+

Restores an array read from the database.

Parameters:

  • array (Array, nil)

    values to coerce to decimals

Returns:

  • (Array<BigDecimal>, Array<Array<BigDecimal>>)

    the coerced array



20
21
22
# File 'app/serializers/array_decimal_serializer.rb', line 20

def self.load(array)
  array_of_decimals(array || [])
end