sodapopcan

sodapopcan

Compile time checking struct keys for a protocol

I have a protocol that is used on Ecto Schemas. The protocol requires that two fields are defined with specific defaults.

I have come up with a working solution that I’m pretty happy with, but I’m just looking for feedback as I’m unsure if this is the optimal way (and maybe I’ve looked past a much simpler solution). In short, I used __after_compile__ and Ecto’s reflection functions to ensure the keys are there.

Obviously one drawback of this is that it must be @derived though I’m not so worried about that.

I’m also wondering about the line %{context_modules: [module]} <- env and if that could have any ramifications. Could there ever be more than one context module in this scenario?

Here is the code:

defmodule MyApp.MyProtocolError do
  defexception [:message]
end

defmodule MyApp.MyProtocolCompile do
  @required_fields [
    name: %{type: :string},
    checked: %{type: :boolean, default: true}
  ]

  def __after_compile__(env, _bytecode) do
    with %{context_modules: [module]} <- env do
      messages =
        for {field, opts} <- required_fields, reduce: [] do
          messages ->
            if module.__schema__(:virtual_type, field) != opts.type do
              message =
                " * #{__MODULE__} must have a field `:#{field}` of type `:#{opts.type}`"

              message =
                message <>
                  ((Map.has_key?(opts, :default) && " and default to `#{opts.default}`") || "")

              [message | messages]
            else
              messages
            end
        end

      if messages != [] do
        raise MyApp.MyProtocolError,
          message: "\n" <> Enum.join(messages, "\n")
      end
    end
  end
end

defprotocol MyApp.MyProtocol do
  def do_it(module)

  @impl true
  defmacro __deriving__(module, options) do
    quote location: :keep do
      @after_compile MyApp.MyProtocolCompile

      defimpl MyApp.MyProtocol, for: unquote(module) do
        def do_it(_module) do
          unquote(options).key
        end
      end
    end
  end
end

The other thing I did was put the __after_compile__ in the __deriving__ so I could just unquote(module) to get the module, but I like this way a bit better.

Where Next?

Popular in Questions Top

Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New

Other popular topics Top

Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44167 214
New

We're in Beta

About us Mission Statement