Get types from struct in compilation time

  • Is there way to get the types from struct defined as bellow, and generate functions based on your types; like binary(), integer()?

  • Can I get the keys of a struct that is marked as “enforced”?

So I have a struct created using TypedStruct like this:

defmodule MyStruct do
	use TypedStruct
	typedstruct do
		field :a, binary(), enforce: true
		field :b, integer()
		# ....
	end
end

And I want generate validation functions/macro of Vex for each field based on your type and if is enforced or not, like this:

defmodule Checker do
  defmacro __usign__(opts) do
    quote do
      [{field, type, enforced?} | _] = my_fields = some_way_to_get_this_types()

      for {field, type, _enforced?} <- my_fields do
        case type do
          "binary()" -> validates(field, by: [function: &is_binary/1, message: "not binary"])
          "integer()" -> validates(field, by: [function: &is_integer/1, message: "not integer"])
        end
      end
    end
  end
end

The result of use Checker will be a bunch of validates injected on module, like this:

defmodule MyStruct do
  use TypedStruct
  use Checker

  typedstruct do
    field(:a, binary(), enforce: true)
    field(:b, binary())
    # ....
  end

  # this will be injected by the `use Checker`
  validates(:a, by: [function: &is_binary/1, message: "not binary"])
  validates(:b, by: [function: &is_integer/1, message: "not integer"])
  # ... and so on
end

In my research I find this, but I dont know hot to deal with this “type tree” to generate types of like MyOtherStruct.t()

@NetonD I think you can get some inspiration from the Domo project, which builds validation functions (packed in Type ensurer modules) for the given struct.

1 Like

Absolutely, already cloned :sunglasses: