Method: AttrJson::Model#serializable_hash

Defined in:
lib/attr_json/model.rb

#serializable_hash(options = nil) ⇒ Object

Override from ActiveModel::Serialization to:

  • handle store_key settings

  • serialize by type to make sure any values set directly on hash still

    get properly type-serialized.

  • custom logic for keeping nil values out of serialization to be more compact

Parameters:

  • strip_nils (:symbol, Boolean)

    (default false) Should we keep keys with nil values out of the serialization entirely? You might want to to keep your in-database serialization compact. By default this method does not -- but by default AttrJson::Type::Model sends :safely when serializing.

    • false => do not strip nils
    • :safely => strip nils only when there is no default value for the attribute, so nil can still override the default value
    • true => strip nils even if there is a default value -- in AttrJson context, this means the default will be reapplied over nil on every de-serialization!


360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/attr_json/model.rb', line 360

def serializable_hash(options=nil)
  strip_nils = options&.has_key?(:strip_nils) ? options.delete(:strip_nils) : false

  unless [true, false, :safely].include?(strip_nils)
    raise ArgumentError, ":strip_nils must be true, false, or :safely"
  end

  super(options).collect do |key, value|
    if attribute_def = self.class.attr_json_registry[key.to_sym]
      key = attribute_def.store_key

      value = attribute_def.serialize(value)
    end

    # strip_nils handling
    if value.nil? && (
       (strip_nils == :safely && !attribute_def&.has_default?) ||
        strip_nils == true )
    then
      # do not include in serializable_hash
      nil
    else
      [key, value]
    end
  end.compact.to_h
end