重构控制器中的案例结构

时间:2016-12-19 15:15:52

标签: elixir phoenix-framework

我在控制器中有以下代码。显然它为重构而尖叫。但我不知道如何解决它。如何重构它以便所有重复的代码部分都消失?

case Repo.insert(changeset) do
  {:ok, social_media_account} ->
    case social_media_account.provider do
      "Twitter" ->
        conn
        |> put_flash(:info, gettext("A"))
        |> redirect(to: user_social_media_account_path(conn, :index, conn.assigns[:user]))
      "GitHub" ->
        conn
        |> put_flash(:info, gettext("B"))
        |> redirect(to: user_social_media_account_path(conn, :index, conn.assigns[:user]))
      _ ->
        conn
        |> put_flash(:info, gettext("C"))
        |> redirect(to: user_social_media_account_path(conn, :index, conn.assigns[:user]))
    end
  {:error, changeset} ->
    render(conn, "new.html", changeset: changeset)
end

1 个答案:

答案 0 :(得分:4)

您可以从case返回一个值并使用:

case Repo.insert(changeset) do
  {:ok, social_media_account} ->
    info = case social_media_account.provider do
      "Twitter" ->
        gettext("A")
      "GitHub" ->
        gettext("B")
      _ ->
        gettext("C")
    end
    conn
    |> put_flash(:info, info)
    |> redirect(to: user_social_media_account_path(conn, :index, conn.assigns[:user]))
  {:error, changeset} ->
    render(conn, "new.html", changeset: changeset)
end