Skip to content

Instantly share code, notes, and snippets.

@jwarlander
Created December 19, 2016 07:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwarlander/f773a795e2f830fbdfbb9f66f992a7fd to your computer and use it in GitHub Desktop.
Save jwarlander/f773a795e2f830fbdfbb9f66f992a7fd to your computer and use it in GitHub Desktop.
Example of dynamic (at compile time) delegation from Erlang-style module to Elixir module
# Actual Elixir module with all the functions
defmodule LibDemo do
def hello(), do: IO.puts "Hello, World!"
def hello(name), do: IO.puts "Hello, #{name}!"
end
defmodule LibDemo.Utils do
def make_args(0), do: []
def make_args(n) do
Enum.map(1..n, fn n -> {String.to_atom("arg#{n}"), [], Elixir} end)
end
end
# Erlang module delegating to the Elixir module
defmodule :lib_demo do
funs =
LibDemo.module_info()[:exports]
|> Enum.filter(fn {fun, _arity} -> not fun in [:__info__, :module_info] end)
for {fun, arity} <- funs do
defdelegate unquote(fun)(unquote_splicing(LibDemo.Utils.make_args(arity))), to: LibDemo
end
end
LibDemo.hello()
LibDemo.hello("Foo")
:lib_demo.hello()
:lib_demo.hello("Foo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment