sodapopcan

sodapopcan

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? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
subsaharancoder
I’ve followed the Phoenix LiveView file upload code here Uploads — Phoenix LiveView v1.0.0-rc.7 and so far everything works just fine wit...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews