Skip to content

Instantly share code, notes, and snippets.

@scudelletti
Created October 25, 2018 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scudelletti/3e9e68b154be16b07edfd5a4461c213d to your computer and use it in GitHub Desktop.
Save scudelletti/3e9e68b154be16b07edfd5a4461c213d to your computer and use it in GitHub Desktop.
Delegates methods to "imported" module on Elixir
defmodule Father do
def sing() do
IO.puts "Lalalalalala"
end
def song(a, b) do
turn_bass_on()
IO.puts "Lelelelelele #{a} #{b}"
end
defp turn_bass_on do
IO.puts "Du Du Dum Du Du Dum"
end
# Delegate functions to Father module based on public Father functions
defmacro __using__(_) do
IO.puts "Functions to define:"
IO.inspect Father.__info__(:functions)
for {name, arity} <- Father.__info__(:functions) do
quote do
defdelegate unquote(name)(unquote_splicing(Macro.generate_arguments(arity, __MODULE__))), to: Father
end
end
end
end
defmodule Son do
use Father
def sing_and_dance do
sing()
IO.puts "Dance...."
end
end
IO.puts String.duplicate("-", 70)
IO.puts "Call sing:"
Son.sing()
IO.puts String.duplicate("-", 70)
IO.puts "Call song:"
Son.song(1,2)
IO.puts String.duplicate("-", 70)
IO.puts String.duplicate("-", 70)
IO.puts "Call sing_and_dance:"
Son.sing_and_dance
IO.puts String.duplicate("-", 70)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment