Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strip nils from Model serialization for more compact representation #175

Merged
merged 5 commits into from
Jan 18, 2023

Conversation

jrochkind
Copy link
Owner

@jrochkind jrochkind commented Jan 12, 2023

We want to mostly keep unnecessary nils out of serializations, to keep them more compact. This will become even more relevant if we move to a full AttrJson::Attributes implementation -- or something semantically like it -- where by default all attributes are included in serialized hash, even if never set. We don't really need to serialize them all in postgres.

  • AttrJson::Model#serializable_hash (and #as_json) now have a new optional strip_attributes keyword argument. Default is false, do same as traditional. true leaves keys for all nil values out of the hash -- but that causes problems for trying to save a nil written on top of another default. So :safely strips nils only for attributes without defaults.

  • The AttrJson::Model::Type type class will by default serialize with :safely -- stripping unnecessary nils. But you can change this with a paramter, that you can also pass to AttrJson::Model#to_type. So for instance, when embedding a model somewhere:

       attr_json :some_model, SomeModel.to_type(strip_nils: false)
       attr_json :some_more_model, SomeModel.to_type(strip_nils: true)
    

    If set to to strip_nils: true, the effect is when deserializing a model with an attribute with a default, the default ends up re-applied on top of previously nil values. Kind of making the default applied not just on original creation, but on every de-serialization too.

@jrochkind jrochkind marked this pull request as ready for review January 12, 2023 21:26
@jrochkind jrochkind merged commit 8836c6b into dev_v2 Jan 18, 2023
@jrochkind jrochkind deleted the strip_nils branch January 18, 2023 20:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant