How to make early return like other languages on Phoenix

tajihiro Source

I would like to return after valid check then go to other page (1). However It seems to goes after, then render index page (2).

def index(conn, %{"id" => id}) do
  unless Model.is_valid!(id) do
      conn
        |> redirect(to: other_path(conn, :other)) #(1)
  end
  # More process are after this.
  render(conn, "index.html") #(2)
end

It seems redirect other page at once, but proceeded after. How can I stop with return like other languages?

elixirphoenix-framework

Answers

answered 1 week ago Dogbert #1

Elixir doesn't have any way to do an early return. You'll have to use unless/else or if/else:

def index(conn, %{"id" => id}) do
  unless Model.is_valid!(id) do
    conn
    |> redirect(to: other_path(conn, :other)) #(1)
  else
    # More process are after this.
    render(conn, "index.html") #(2)
  end
end

If you don't want an extra level of indentation the best you can do is create another function and call it in the else block.

comments powered by Disqus