Created
December 19, 2016 07:50
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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