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

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
vegabook
I'm brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30840 112
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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

We're in Beta

About us Mission Statement