What is the purpose of alias a module inside the same module?

Hi, I am following the Programming Phoenix book and trying out different generators.

When I use the phx.gen.json generator, it created a view file that alias itself and I don’t understand what does it do and why it is needed.

the specific part that I don’t understand:

defmodule RumblWeb.FooView do
  use RumblWeb, :view
  alias RumblWeb.FooView

the full file:

defmodule RumblWeb.FooView do
  use RumblWeb, :view
  alias RumblWeb.FooView

  def render("index.json", %{foos: foos}) do
    %{data: render_many(foos, FooView, "foo.json")}
  end

  def render("show.json", %{foo: foo}) do
    %{data: render_one(foo, FooView, "foo.json")}
  end

  def render("foo.json", %{foo: foo}) do
    %{
      id: foo.id,
    }
  end
end

Specifically, it makes this line work, where it can refer to FooView instead of RumblWeb.FooView. It could also do __MODULE__, but my guess is that the book just didn’t want to have to worry about introducing what __MODULE__ is.

5 Likes

Thanks for explanation, I completely overlooked the little FooView reference, haha.
(P.S. The book does introduce __MODULE__)