Mateusz Urbański
Mateusz Urbański

Reputation: 7882

Elixir code refactor

I have the following View in Phoenix app:

defmodule TattooBackend.Web.API.V1.AccountView do
  use TattooBackend.Web, :view

  alias TattooBackend.Repo

  def render("my_account.json", %{account: account}) do
    account = account |> Repo.preload(:studio)
    studio  = account.studio

    data = %{
      id: account.id,
      email: account.email,
    }

    if account.studio do
      data = studio_data(data, studio)
    end

    if true do
      data = Map.put(data, :test_key, %{})
    end

    data
  end

  defp studio_data(data, studio) do
    studio  = studio |> Repo.preload(:address)
    address = studio.address

    studio_data = %{
      id: studio.id,
      name: studio.name,
      address: "#{address.street}, #{address.city} #{address.zip_code}"
    }

    Map.put(data, :studio, studio_data)
  end
end

Everything is working as expected but in console I see the following warning:

warning: the variable "data" is unsafe as it has been set inside a case/cond/receive/if/&&/||. Please explicitly return the variable value instead.

How can I refactor this?

Upvotes: 1

Views: 66

Answers (1)

Tyler Willingham
Tyler Willingham

Reputation: 559

The warning is indicating that you should write your conditional in such a way that the return of the conditional is what gets assigned, rather than doing assignment inside of the conditional itself.

data = if 5 > 1 do
         "best data"
       else
         "boring data"
       end

Upvotes: 1

Related Questions