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

Idea for refactor of json properties #4

Open
beta-ziliani opened this issue Aug 27, 2024 · 0 comments
Open

Idea for refactor of json properties #4

beta-ziliani opened this issue Aug 27, 2024 · 0 comments

Comments

@beta-ziliani
Copy link
Member

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant