cjbottaro

cjbottaro

How to programmatically call macros?

I want to programmatically generate input objects from introspecting my schema, but I can’t figure out the metaprogramming to do so.

Essentially, I want this desired module def:

defmodule InputObjects do
  use Absinthe.Schema.Notation

  input_object :user_filter do
    field :id, :integer_filter
    field :email, :string_filter
  end
end

But from coming from variables:

defmodule InputObjects do
  use Absinthe.Schema.Notation

  name = :user_filter
  fields = [
    {:id, :integer_filter},
    {:email, :string_filter}
  ]
  
  input_object name do
    Enum.each fields, fn {name, type} ->
      field name, type
    end
  end
end

How to do this? Thanks for the help!

Marked As Solved

Eiji

Eiji

@cjbottaro The problem with absinthe is that they are using macros and work only with raw data (not in variables).

defmodule Example do
  defmacro sample(some_data) do
    {:here, [], [:just, :goes, :ast, :without, :quote]}
  end
end

# instead of:

defmodule Example do
  defmacro sample(some_data) do
    quote bind_quoted: [some_data: some_data], unquote: false do
      here(:just, :goes, :normal, :data, :not, :in, :ast, :format, some_data)
    end
  end
end

This is because absinthe is making some checks on raw data.

Let’s say we have such simple code:

defmodule Example do
  defmacro sample(data) do
    IO.inspect(data)
  end
end

Example.sample(5)
5 # IO.inspect call here
5

# vs

data = 5         
5
Example.sample(data)
{:data, [line: 8], nil} # IO.inspect call here
5

As you can see it’s not possible to work on it without proper quoting. Same goes if you want to use absinthe macros i.e. you need to pass raw data.

However this does not mean that it’s not possible to pass variables - this only means that we need pass raw data to absinthe macros. It should be hint for more experienced developers. Just write your own macro!

Firstly you need to know what AST you need to return:

# inside iex call
quote do
  # code of which ast you want to preview
end

# for example:
quote do
  input_object :user_filter do
    field :id, :integer_filter
    field :email, :string_filter
  end
end

{:input_object, [],
 [
   :user_filter,
   [
     do: {:__block__, [],
      [
        {:field, [], [:id, :integer_filter]},
        {:field, [], [:email, :string_filter]}
      ]}
   ]
 ]}

Let’s split it:

  1. {:field, [], [:id, :integer_filter]}
    As you can see it’s field/2 macro AST

  2. {:__block__, [], […]}
    Block here is list of AST expressions inside function which are not single literals. For example: def sample(…) do 5 end gives us just raw 5 in place of whole :__block__ part, but if we add one more line with same literal they would be arguments in :__block__ AST.

  3. Finally {:input_object, [], [:user_filter, [do: …]]}
    Similarly to 1st point it’s ast for input_object/2 call. Here do … end goes to 2nd argument which is keyword list [do: …]. As in 2nd point we could have: [do: 5] or [do: {:__block__, [], […]}]. For us it’s 2nd case as we will never contain literals there.

From this here goes example code:

defmodule Example do
  defmacro sample do
    name = :user_filter

    fields = [
      [:id, :integer_filter],
      [:email, :string_filter]
    ]

    data = Enum.map(fields, &Example.ast_call(:field, &1))
    block = Example.ast_call(:__block__, data)
    do_block_keyword = [do: block]
    Example.ast_call(:input_object, [:user_filter, do_block_keyword])
    # since you generated AST you do not need `quote do … end` here
  end

  # in same way you can simply create helper functions
  # for specific absinthe calls,
  # so you can minimize your initial data (i.e. no need to pass empty list as 2nd argument in each ast_call)
  # and your code is more readable
  def ast_call(name, args), do: {name, [], args}

  # for example:
  # def field_ast(name, type), do: {:field, [], [name, type]}
end

and here is usage:

defmodule InputObjects do
  use Absinthe.Schema.Notation
  require Example
  Example.sample()
end

Sorry if I made any typo - I wrote everything from memory. :077:

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