vrod

vrod

First time Elixir macro -- generate similar functions?

This is my first time I am looking at macros. I think I understand they are something like “pre generation” of code. Maybe something like using PHP templates to make Javascript code – they make Elixir code before it runs? OK this is maybe a bad example.

What I am trying to do is this: I have multiple functions that are almost all the same. Each one gets a thing from an API. Each one is the same, but each one returns a different struct. All of them look like this:

defmodule Thing1Resolver do
   def get_one(args) do
     data = get_from_api(args)
     struct(Thing1, args)
   end
end

The only difference is the module Thing1 is different for each function (Thing2, Thing3, Thing4). Can I write a macro to use and build functions like this? So maybe my resolver modules look like

defmodule Thing1Resolver do
    use Shared, struct: Thing1
end

Is this possible? Maybe it is a bad idea. I want to understand how it works and then I can decide.

Thankyou

Most Liked

al2o3cr

al2o3cr

You could use macros for this, but since it’s really just substituting a value for thing it’s not a great fit.

Macros are really powerful when you want a piece of code to generate multiple related functions / data, or code that depends on the whole module’s settings. For instance, the Ecto.Schema.schema macro generates __changeset__ and __schema__ functions after all the schema fields are defined along with setting many module attributes.

al2o3cr

al2o3cr

Because this:

defmodule FooBar.Thing1Resolver do
  use FooBar.Share, struct: FooBar.Thing1
  import FooBar.Creator

  defcreate(FooBar.Thing1)
end

is harder to read than this:

defmodule FooBar.Thing1Resolver do
   def new(args) do
    struct(FooBar.Thing1), args)
  end

  def create(args) do
    struct(FooBar.Thing1), args)
  end
end

For instance, it’s considerably less obvious the functions generated in Thing1Resolver in the first version are identical since their definitions are split among two modules and use arguments differently.

Another approach to consider: put as little code in the macro as possible and call out to the real implementation. This is part of what happens when you say use Ecto.Repo in your application:

defmodule FooBar.Share do
  defmacro __using__(opts) do
    struct_name = opts[:struct]

    quote do
      def new(args) do
        FooBar.Share.new(unquote(struct_name), args)
      end
    end
  end

  def new(struct_name, args) do
    struct(struct_name, args)
  end
end

defmodule Wat do
  use FooBar.Share, struct: Wat

  defstruct [:val]
end

Wat.new(val: 1)

Here the macro generates a function which adds in the argument passed to use but delegates all the functionality to a function defined on FooBar.Share. There’s a tiny compilation space/performance improvement since less AST is generated, and there’s less thinking about tricky things with unquote.

John-Goff

John-Goff

Why not just have a function that takes the type of struct? Something like

def get_generic(thing, args) do
  data = get_from_api(args)
  struct(thing, args)
end

Also note with this code you’re not using the API result for anything, and it’s essentially doing nothing, assuming there are no side effects from that API call.

Where Next?

Popular in Questions Top

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
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
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
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

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
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 30877 112
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 Postgres...
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
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement