After years of not practicing with macros, I recently decided to make a small project with it once again. something like typed_struct/lib/typed_struct.ex at main · ejpcmac/typed_struct · GitHub . I have read the codes but it is very magic for me at first glance.
Imagine you have this code:
defmodule ExampleUsage do
import MishkaPub.ActivityStream.TypedStruct
typedstruct do
field(:name1, type: String.t(), required: true)
field(:name2, type: DateTime.t(), required: false, default: "shahryar")
field(:name3, type: list(string()), required: true)
end
end
I need to get all fields and convert them as a map like this:
[
%{title: :name1, type: String.t(), required: true},
%{title: :name2, type: DateTime.t(), required: false, default: "shahryar"},
%{title: :name3, type: list(string()), required: true},
]
So I created a macro like this:
defmacro typedstruct(do: ast) do
fields_ast =
case ast do
{:__block__, [], fields} -> fields
field -> [field]
end
Enum.map(fields_ast, fn field ->
IO.inspect(field) # I could not be able to convert it
end)
end
For example the pattern of
astis not equal always to let me create a pattern, and some times user putsString.t()some times they putlist(string()), again it is different
It should be noted, at first I just want to create something like this and after that I want to create t() type and struct inside a module. but I need to go step by step.
Thank you for your help in advance






















