From 2f41457cfbdf22923e80bfdb64754dcedb1e9bb9 Mon Sep 17 00:00:00 2001 From: Ali Naqvi Date: Sun, 16 Apr 2023 23:16:12 +0800 Subject: [PATCH] feat: add support for including fields in json serde when persistence flag is off --- shard.yml | 2 +- src/active-model/model.cr | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/shard.yml b/shard.yml index cbe7c2a..ece90ff 100644 --- a/shard.yml +++ b/shard.yml @@ -1,5 +1,5 @@ name: active-model -version: 4.3.0 +version: 4.3.1 crystal: ">= 1.0.0" license: MIT diff --git a/src/active-model/model.cr b/src/active-model/model.cr index 2cf271d..d5b230b 100644 --- a/src/active-model/model.cr +++ b/src/active-model/model.cr @@ -241,7 +241,7 @@ abstract class ActiveModel::Model {% name = kv[0] %} {% opts = kv[1] %} %value = @{{name}} - json.field({{ name.stringify }}) do + json.field({{ (opts[:tags] && opts[:tags][:json_key]) || name.stringify }}) do {% if opts[:converter] %} if !%value.nil? {{ opts[:converter] }}.to_json(%value, json) @@ -530,7 +530,7 @@ abstract class ActiveModel::Model def after_initialize(trusted : Bool) if !trusted {% for name, opts in FIELDS %} - {% if !opts[:mass_assign] %} + {% if !opts[:mass_assign] && !opts[:show] %} @{{name}} = nil {% end %} {% end %} @@ -705,6 +705,7 @@ abstract class ActiveModel::Model name, mass_assignment = true, persistence = true, + show = false, serialization_group = [] of Symbol, **tags, &block @@ -721,7 +722,7 @@ abstract class ActiveModel::Model # Assign instance variable to correct type @[JSON::Field( presence: true, - ignore: {{ !persistence }}, + ignore: {{ !show && !persistence }}, key: {{tags[:json_key]}}, emit_null: {{tags[:json_emit_null]}}, root: {{tags[:json_root]}}, @@ -729,7 +730,7 @@ abstract class ActiveModel::Model )] @[YAML::Field( presence: true, - ignore: {{ !persistence }}, + ignore: {{ !show && !persistence }}, key: {{tags[:yaml_key]}}, emit_null: {{tags[:yaml_emit_null]}}, {{**tags}} @@ -768,6 +769,7 @@ abstract class ActiveModel::Model klass: resolved_type, converter: tags[:converter], mass_assign: mass_assignment, + show: show, should_persist: persistence, serialization_group: serialization_group, tags: tags.empty? == true ? nil : tags, @@ -780,6 +782,7 @@ abstract class ActiveModel::Model klass: resolved_type, converter: tags[:converter], mass_assign: mass_assignment, + show: show, should_persist: persistence, serialization_group: serialization_group, tags: tags.empty? == true ? nil : tags,