m.cichacz
m.cichacz

Reputation: 759

Elixir's use with function name

Recently I've stumbled upon this code

defmodule MyAppWeb.PageLive do
  use MyAppWeb, :live_view

It's part of default app generated with Phoenix Live View (mix phx.new --live).
It's first time when I see the use construct with a function name as a second argument.
I've tried to search the web on some docs about it but couldn't find a proper naming for this.

Can you help me understand what happens when this executes?

It doesn't call __using__ macro but calls a function instead, and I'm not sure whether I can pass some options there, or I need to use the "normal" way (with __using__ macro). I've tried something like use MyAppWeb, :live_view, opts but that raises undefined function use/3

Upvotes: 2

Views: 363

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

__using__/1 is just a macro, and use Mod, args is just syntactic sugar for Mod.__using__(args).

It doesn't call __using__/1 macro but calls a function instead [...]

Plain wrong, it calls MyAppWeb.__using__/1 macro.

If you’d open your (also generated) MyAppWeb, you’ll find there somewhat like

  defmacro __using__(which) when is_atom(which) do
    apply(__MODULE__, which, [])
  end

That said, you might call which directly, or amend MyAppWeb.__using__/1 to accept arguments.

Upvotes: 4

Related Questions