The Crystal Programming Language Forum

Define type in a variable

I am trying to define a JSON.mapping withing a struct. I have some time fields in the record obtained from the database, which I would like to convert to millisecond timestamp when converted to JSON. I know about the awesome EpochMillisConverter. That is, the following works:

struct Rec
     JSON.mapping(
          mytimefield: {type: Time?, converter: EpochMillisConverter}
          anothertimefield: Time?
          yetanothertimefield: Time?
      )
end

My question is: can I assign {type: Time?, converter: EpochMillisConverter} to a variable that I can use for all the three time fields, instead of repeating it for every time field. I tried assigning {type: Time?, converter: EpochMillisConverter} to a constant, but that does not work. I also tried property time_type = {type: Time?, converter: EpochMillisConverter}, but that also throws error saying expecting token 'CONST'.

TIME_TYPE = {type: Time?, converter: EpochMillisConverter}

struct Rec
  {% begin %}
     JSON.mapping(
          mytimefield: {{TIME_TYPE}},
          anothertimefield: {{TIME_TYPE}},
          yetanothertimefield: {{TIME_TYPE}},
      )
  {% end %}
end

This would work. Although I would just duplicate the converter.

EDIT: Updated based on @asterite comment.

1 Like

No need to use macro finished. You just need to enter macro mode, you can do that with {% begin %}… {% end %}

1 Like

Also, you should avoid macros as much as possible. Just a little duplication is fine.

1 Like

Thank you @asterite and @Blacksmoke16.
Yes, I would just repeat it as you advised, if it is not possible to do with standard variables. At the same time, it is good to know (for something else), how macros can be used.

Thanks again.