Do you have any suggestions to how I can make this cleaner?
Video params is from a form submission, so a map as %{"url" => "https://youtube.com/......", "title" => "Carneval in Rio de Janeiro", ...}
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
Here is my create
method if it is of any use:
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