salsify/avromatic

Avro array insert

Closed this issue · 2 comments

Hello,

I have a couple of avro messages - User & UserList

{
  "type": "record",
  "name": "user",
  "fields": [
    {
      "name": "id",
      "type": "int"
    },
    {
      "name": "name",
      "type": "string"
    },
    {
      "name": "email",
      "type": "string"
    }
  ]
}
{
  "type": "record",
  "name": "user_list",
  "fields": [
      {
        "name": "users",
        "type": {
            "type": "array",
            "items": "user"
        }
      }
  ]
}

I am using Avromatic to build the Ruby model. However, When I try to insert in to the UserList, the users field is NilClass. Hence, the insert in to array fails for a new User.

user = Avro::User.new(id: 1, name: "Joe", email: "joe@nocode.com")
userList = Avro::User.new
userList.users << user

Why users field on UserList is not an array? What am I doing wrong?

UserList#users is defaulting to nil since there's no Avro default. You can fix this with any of the following:

  1. Explicitly construct the UserList with a non-nil array e.g. UserList.new(users: [])
  2. Override the UserList#initialize method to default the array
  3. Change your Avro schema to set a default value UserList#users to []

I'd recommend doing 3 if you want all clients of this schema to have that behavior.

Thanks for the prompt answer. It works now.