Skip to content

Idea for refactor of json properties #4

@beta-ziliani

Description

@beta-ziliani

I found several JSON fields that are present with different formats. This is handle by a union of two properties:

    @[JSON::Field(key: "final_evaluation")]
    property final_evaluation_1 : String?
    @[JSON::Field(key: "finalEvaluation")]
    property final_evaluation_2 : String?

    def final_evaluation : String
      unless result = final_evaluation_1 || final_evaluation_2
        raise "Invalid final_evaluation"
      end
      result
    end

A potential refactor could be a macro:

require "json"

struct IpaProof
  include JSON::Serializable
  
  macro two_names_json_prop(name1, name2, ty)
    @[JSON::Field(key: {{name1}})]
    property {{name1}}_1 : {{ty}}?
    
    @[JSON::Field(key: {{name2}})]
    property {{name1}}_2 : {{ty}}?
    
      def {{name1}} : {{ty}}
        {{name1}}_1 || {{name1}}_2 || raise "Invalid or missing key {{name1}}"
      end
  end

  two_names_json_prop final_evaluation, finalEvaluation, String?
end

a = IpaProof.from_json %({"finalEvaluation": "hi"})
puts a.final_evaluation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions