svilen

svilen

Author of Concurrent Data Processing in Elixir

Dynamically add module functions in __using__ macro

I have a bunch of functions in a module, that I’d like to dynamically add to a __using__ macro:

defmodule A do
  defmacro __using__(_opts) do
    quote do
      # Dynamically add 
      # def foo(), do: "Foo"
      # and any other functions.
    end
  end

  def foo(), do: "Foo"
end

My goal is to have the functions accessible on the original module, inject them into the module that’s using it via use and make them overridable:

I’m just starting with metaprogramming so I’d appreciate any solutions or pointers in the right direction. Thanks!

Marked As Solved

kip

kip

ex_cldr Core Team

If basically you want to delegate a bunch of functions to another module, have them available as public functions on the new module and also make them overridable then perhaps the following would work? Its not considered good practise to do defining lots of functions in a quote block.

defmodule A do
  defmacro __using__(_opts) do
    quote do
      defdelegate foo(), to: A
      
      defoverridable [foo: 0]
    end
  end
  
  def foo(), do: "Foo"
end

defmodule B do
  use A
end

Also Liked

jswny

jswny

I’m pretty sure you can just import the parent module of the __using__ macro with import A inside the macro. For example, the Phoenix 1.3 generators create the following DataCase module:

defmodule MyApp.DataCase do

  using do
    quote do
      ...

      import MyApp.DataCase
    end
  end

  def errors_on(changeset) ...
end

So, all of the MyApp.DataCase functions will be auto imported into the scope of any module which calls use MyApp.DataCase.

idi527

idi527

https://hexdocs.pm/elixir/Kernel.html#defoverridable/1 has an example similar to what you want:

defmodule A do
  defmacro __using__(_opts) do
    quote do
      def foo, do: "Foo"

      defoverridable [foo: 0]
    end
  end
end

defmodule B do
  use A

  def foo do
    super() <> "Bar"
  end
end

And then in the shell

iex(1)> B.foo()
"FooBar"
kip

kip

ex_cldr Core Team

import makes the functions from A available in module B but it doesn’t re-export them. Therefore functions in B can invoke the imported functions from A but you can’t call them from outside B. Its nothing to do with use, its how import works.

Overall, your last example isn’t a strong justification for use. Just import would be preferred because the intent is clearer. But I recognise your use case if presumably more complex that just import.

kip

kip

ex_cldr Core Team

I sort of understand your intent but, to me (and maybe only me), this smells a bit of “making magic”. And the language “inherit/extend” makes it seem even more so.

I’ve found that a combination of partial importing of functions and the occasional use of defdelegate is a lot clearer to me because its explicit. One of the most frustrating things is to see a function call to a function whose definition you can’t find. The multiple indirect usees would, for me, make the intent obscure and quite frustrating.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
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
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
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
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement