Sha256: e1601393cac7164ce697cf04d8dd53780aa092afe7d8c07db4604cb30d69f4d8

Contents?: true

Size: 735 Bytes

Versions: 5

Compression:

Stored size: 735 Bytes

Contents

# frozen_string_literal: true

# @private
module PGTrunk::Serializers
  # @private
  # Cast the attribute value as an array of strings.
  # It knows how to cast arrays returned by PostgreSQL
  # as a string like '{USD,EUR,GBP}' into ['USD', 'EUR', 'GBP'].
  class ArrayOfHashesSerializer < ActiveRecord::Type::Value
    def cast(value)
      case value
      when ::String then JSON.parse(value).map(&:symbolize_keys)
      when ::NilClass then []
      when ::Array then value.map(&:to_h)
      else [value.to_h]
      end
    end

    def serialize(value)
      Array.wrap(value).map { |item| item.to_h.symbolize_keys }
    end
  end

  ActiveModel::Type.register(
    :pg_trunk_array_of_hashes,
    ArrayOfHashesSerializer,
  )
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
pg_trunk-0.2.0 lib/pg_trunk/core/serializers/array_of_hashes_serializer.rb
pg_trunk-0.1.3 lib/pg_trunk/core/serializers/array_of_hashes_serializer.rb
pg_trunk-0.1.2 lib/pg_trunk/core/serializers/array_of_hashes_serializer.rb
pg_trunk-0.1.1 lib/pg_trunk/core/serializers/array_of_hashes_serializer.rb
pg_trunk-0.1.0 lib/pg_trunk/core/serializers/array_of_hashes_serializer.rb