How does the JSON.mapping macro work with union argument types?

The JSON.mapping documentation explicitly states that the property value typemust be of the same type. However, in practice the types of trade unions also operate:

json1 = %q({"ok": true, "result": [{"type": "update", "id": 1}, {"type": "update", "id": 2}]})
json2 = %q({"ok": true, "result": {"type": "message"}})

class Response
  JSON.mapping({
    ok: Bool,
    result: Message | Array(Update)
  })
end

class Update
  JSON.mapping({
    type: String,
    id: Int32
  })
end

class Message
  JSON.mapping({
    type: String
  })
end

A call Response.from_jsonin a JSON string displays the expected result.

Response.from_json json1

will output:

#<Response:0x10d20ce20
  @ok=true,
  @result=
  [#<Update:0x10d20cc60 @id=1, @type="update">,
   #<Update:0x10d20cbe0 @id=2, @type="update">]>

and

Response.from_json json2

will output:

#<Response:0x10d20c180
  @ok=true,
  @result=#<Message:0x10e241f80 @type="message">>

My question is, how does it work? Is behavior or an occasional unreliable function expected?

+4
source share
1 answer

The documentation is expected to be incorrect.

0
source

Source: https://habr.com/ru/post/1691527/


All Articles