From 826a631d468ba119ec0cc31c9f173fba40ed7716 Mon Sep 17 00:00:00 2001 From: analogsalad Date: Wed, 5 Oct 2022 14:15:52 +0300 Subject: [PATCH] Document `after_initialize` method for `yaml` and `json` serializers (#12530) --- src/json/serialization.cr | 22 ++++++++++++++++++++++ src/yaml/serialization.cr | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/json/serialization.cr b/src/json/serialization.cr index 450a15287236..0e7ff1782737 100644 --- a/src/json/serialization.cr +++ b/src/json/serialization.cr @@ -126,6 +126,28 @@ module JSON # field, and the rest of the fields, and their meaning, depend on its value. # # You can use `JSON::Serializable.use_json_discriminator` for this use case. + # + # ### `after_initialize` method + # + # `#after_initialize` is a method that runs after an instance is deserialized + # from JSON. It can be used as a hook to post-process the initialized object. + # + # Example: + # ``` + # require "json" + # + # class Person + # include JSON::Serializable + # getter name : String + # + # def after_initialize + # @name = @name.upcase + # end + # end + # + # person = Person.from_json %({"name": "Jane"}) + # person.name # => "JANE" + # ``` module Serializable annotation Options end diff --git a/src/yaml/serialization.cr b/src/yaml/serialization.cr index f87eae8c39f1..6b08d525d171 100644 --- a/src/yaml/serialization.cr +++ b/src/yaml/serialization.cr @@ -125,6 +125,28 @@ module YAML # field, and the rest of the fields, and their meaning, depend on its value. # # You can use `YAML::Serializable.use_yaml_discriminator` for this use case. + # + # ### `after_initialize` method + # + # `#after_initialize` is a method that runs after an instance is deserialized + # from YAML. It can be used as a hook to post-process the initialized object. + # + # Example: + # ``` + # require "yaml" + # + # class Person + # include YAML::Serializable + # getter name : String + # + # def after_initialize + # @name = @name.upcase + # end + # end + # + # person = Person.from_yaml "---\nname: Jane\n" + # person.name # => "JANE" + # ``` module Serializable annotation Options end