We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
The Module Behind the Curtain
spapiernik
0 comments
Copy link
Use defdelegate when a function should simply forward its arguments to another module.
defmodule Users do
defdelegate get(id), to: Accounts
end
This is equivalent to writing:
defmodule Users do
def get(id), do: Accounts.get(id)
end
defdelegate is useful when you want to expose a function through a public API without duplicating its implementation.
You can also rename the delegated function:
defmodule User do
defdelegate find_user(id), to: Accounts, as: :get
end
This calls Accounts.get(id) when Users.find_user(id) is invoked.
A good rule of thumb: use defdelegate when the function exists purely as a forwarding layer; if you need additional logic, define the function normally.
copied to clipboard