2017-06-21 93 views
1

我在凤凰应用中的以下观点:药剂代码重构

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. 

我如何重构呢?

+1

https://stackoverflow.com/questions/39550644/elixir-set-variable-in-if-statement – Dogbert

回答

1

该警告表明您应该以这样的方式编写条件,即条件的返回值是指定的值,而不是在条件本身内部进行赋值。

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