Need a suggestion to create a pattern match by accepting optional parameters

shahryarjb
Fri, 11 Aug 2023 08:29:45 +0000
Questions / Help

Hello, I have been developing a simple macro and now I want to improve it and let it accept nested option.

For example:

guardedstruct do
  field(:id, String.t(), derive: "sanitize(trim, strip_tags) validate(string)")
  field(:url, String.t())
  field(:published, map()) do
    field(:type, String.t(), enforce: true)
    field(:updated, DateTime.t())
    field(:like, map()) do
      field(:id, String.t(), derive: "sanitize(trim, strip_tags) validate(string)")
      field(:updated, DateTime.t())
    end
  end
end

If you see the code, I have 2 diffrent field macro, one of them is without do and another has do.

So I tried some thing like this, but these have conflict multiple clauses

First way

  defmacro field(name, type, [do: block] = opts) do
  end

  defmacro field(name, type, opts \\ []) do
  end

Second way:

  defmacro field(name, type, opts \\ [], do: block) do
  end

  defmacro field(name, type, opts \\ []) do
  end

It has compiler error, so I want to find it is possible to create pattern instead of using Keyword.has_key?

Thanks, you can see my project here: https://github.com/mishka-group/mishka_developer_tools/blob/master/lib/macros/guarded_struct.ex

8 posts - 2 participants