我在Phoenix应用程序中有以下视图:
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
一切都按预期工作,但在控制台中我看到以下警告:
warning: the variable "data" is unsafe as it has been set inside a case/cond/receive/if/&&/||. Please explicitly return the variable value instead.
我该怎么重构呢?
答案 0 :(得分:1)
警告表明你应该以这样的方式编写条件:条件的返回是指定的,而不是在条件本身内部进行赋值。
data = if 5 > 1 do
"best data"
else
"boring data"
end