Class: IntegerKeyHashSerializer

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

Overview

Serializer for JSONB columns that store { integer_key => value } hashes,
typically { item_id => quantity } in Packing#contents.

PostgreSQL JSONB always deserializes object keys as strings. This serializer
normalises them back to integers on load so callers can use integer IDs
naturally (e.g. contents[item.id]) without string/integer fallback hacks.

Handles both shapes the contents column can take:
Hash — single-box { item_id => qty, … }
Array — multi-box [{ item_id => qty }, { item_id => qty }, …]

Class Method Summary collapse

Class Method Details

.dump(value) ⇒ Hash, ...

Prepares the value for database storage (stored as-is; JSONB stringifies keys).

Parameters:

  • value (Hash, Array<Hash>, nil)

    the value to store

Returns:

  • (Hash, Array<Hash>, nil)

    the value unchanged



18
19
20
# File 'app/serializers/integer_key_hash_serializer.rb', line 18

def self.dump(value)
  value
end

.load(raw) ⇒ Hash{Integer => Object}+

Restores a value read from the database, converting hash keys back to integers.

Parameters:

  • raw (Hash, Array<Hash>, String, nil)

    the raw stored value

Returns:

  • (Hash{Integer => Object}, Array<Hash{Integer => Object}>)

    the value with integer keys



26
27
28
# File 'app/serializers/integer_key_hash_serializer.rb', line 26

def self.load(raw)
  normalize(HashSerializer.load(raw))
end