Skip to content

Generic Codec #68

@fogfish

Description

@fogfish

We do have a ADT - Erlang record

-record(adt, {id, title, ...}).

external serialization works with maps

jsx:encode(#{<<"id">> => ..., <<"title">> => ...})

How to automate process of ADT to maps and back transformation

-ifndef(decode).
-define(decode(Type, Struct),
   list_to_tuple([Type | 
      [lens:get(lens:at(typecast:s(X)), Struct) || X <- record_info(fields, Type)]]
   )
).
-endif.

-ifndef(encode).
-define(encode(Type, Struct),
   maps:from_list(
      [{typecast:s(Key), Value} ||
         {Key, Value} <- lists:zip(
            record_info(fields, Type),
            tl(tuple_to_list(Struct))
         ),
         Value /= undefined,
         Value /= null
      ]
   )
).
-endif.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions