sheharyarn

sheharyarn

Define functions in module metaprogrammically

I have three identical methods in my module, that do (almost) exactly the same thing. Instead of repeating the function definitions, I am trying to define them once to keep code minimal and same for all of them.

So far I’ve tried using Code.eval_string:

defmodule MyModule do
  Enum.each ~w(method1 method2 method3), fn method ->
    @method method

    Code.eval_string """
      def #{@method}(map) when is_map(map) do
        do_map_stuff(:#{@method}, map)
      end

      def #{@method}(arg) do
        do_other_stuff(:#{@method}, arg)
      end
    """
  end

  ## Other Methods

end

but this throws ArgumentError:

Compiling 1 file (.ex)
** (ArgumentError) cannot invoke def/2 outside module
    (elixir) lib/kernel.ex:4297: Kernel.assert_module_scope/3
    (elixir) lib/kernel.ex:3299: Kernel.define/4
    (elixir) expanding macro: Kernel.def/2
    nofile:1: (file)

I think quote/unquote might be the way to go, but I’m not exactly sure how to do this using them (I’ve already read the Meta Guide on the Elixir website).

Most Liked

alxndr

alxndr

Don’t need to use Code.eval_string; you can wrap a def in a “loop” and use unquote/1 to “extract” the variable into the context that you’re def-ing in:

defmodule M do
  Enum.each ~w(foo bar), fn(method_name) ->
    def unquote(:"#{method_name}")(), do: unquote(method_name)
  end
end
vic

vic

Asdf Core Team

There’s no need to use eval_string, you could use Code.eval_quoted but it’d be much much better to just define a macro in another module and then import it.

Here’s a quick example, you can put on a file foo.ex and execute with elixir.

defmodule Gen do

  # Note that macro arguments and return values are quoted expressions
  defmacro gen({name, _, _}) do
    quote do

      # here we define it dinamically
      def unquote(name)() do
        IO.inspect(unquote(name))
      end

    end
  end
end

defmodule Foo do
  import Gen
  gen foo
end

Foo.foo

Last Post!

sheharyarn

sheharyarn

Thank you. Someone just posted this as an answer on my SO question as well.

http://stackoverflow.com/a/40250462/1533054

Where Next?

Popular in Questions Top

baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
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
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
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
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New

Other popular topics Top

grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54092 488
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54996 245
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44167 214
New

We're in Beta

About us Mission Statement