清理Elixir / Phoenix地图替换代码

时间:2016-05-21 09:41:08

标签: elixir phoenix-framework

你对我如何制作这种清洁剂有什么建议吗?

视频参数来自表单提交,因此地图为%{“url”=> “https://youtube.com/ ......”,“title”=> “里约热内卢的卡内瓦尔”,......}

defp make_url_ready_for_embedding(video_params) do
  cond do
    String.contains? video_params["url"], "/watch?v=" ->
      video_params |> Map.put("url", String.replace(video_params["url"], "/watch?v=", "/embed/"))
    String.contains? video_params["url"], "https://vimeo.com" ->
      video_params |> Map.put("url", Regex.replace(~r/([^1-9]+)/, video_params["url"], "https://player.vimeo.com/video/"))
    true ->
      video_params
  end
end

以下是我的create方法,如果它有用:

def create(conn, %{"video" => video_params}, user) do
    changeset = 
      user
      |> build_assoc(:videos)
      |> Video.changeset(video_params |> make_url_ready_for_embedding)

    case Repo.insert(changeset) do
      {:ok, _video} ->
        conn
        |> put_flash(:info, "Video created successfully.")
        |> redirect(to: video_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

1 个答案:

答案 0 :(得分:2)

逻辑是有道理的,但线条很长。

我可能会选择类似的东西:

defp make_url_ready_for_embedding(%{"url" => url} = video_params) do
  url = cond do
    String.contains?(url, "/watch?v=") ->
      String.replace(url, "/watch?v=", "/embed/")
    String.contains?(url "https://vimeo.com") ->
      Regex.replace(~r/([^1-9]+)/, url, "https://player.vimeo.com/video/")
    true ->
      url
  end
  %{video_params | "url" => url)
end

这是更好的,但目的仍然不是很清楚。我可能会考虑使用函数来帮助解决这个问题:

defp make_url_ready_for_embedding(%{"url" => url} = video_params) do
  type = cond do
    youtube_video?(url) -> :youtube
    vimeo_video?(url)   -> :vimeo
    true                -> :unknown
  end
  %{video_params | "url" => transform_url(url, type)}
end

defp youtube_video?(url) do
  String.contains?(url, "/watch?v=")
end

defp vimeo_video?(url) do
  String.contains?(url, "https://vimeo.com")
end

defp transform_url(url, :unknown) do: url
defp transform_url(url, :youtube) do
  String.replace(url, "/watch?v=", "/embed/")
end
defp transform_url(url, :vimeo) do
  Regex.replace(~r/([^1-9]+)/, url, "https://player.vimeo.com/video/")
end

这样做的好处是,您可以测试transform_url函数(使其公开,@ doc为false),以确保为每种类型正确转换网址。