Using 'with' keyword

Hey guys,

So, I finally wanted to remove a whole load of indented ‘case’ statements using ‘with’. Problem is, it doesn’t seem to work as I expect. Here’s an example:

def update(conn, %{"id" => id, "casestudy" => params}) do
  su = get_session(conn, :current_user)
  casestudy = Casestudy.for_company(id, su.company_id)

  with
    true <- valid_file_params(params),
    {:ok, file} <- Repo.update(File.changeset(casestudy.file, %{"title" => params["file"].filename, "filename" => make_filename(params)})),
    {:ok, _casestudy} <- Repo.update(Casestudy.changeset(casestudy, %{"title" => params["title"]})),
    do: do_update(conn, params)
  else
    false ->
      redirect(conn, to: account_path(conn, :show, su.company_id))
    {:error, _} ->
      conn
      |> put_flash(:info, "Casestudy could not be updated. Please contact an administrator.")
      |> redirect(to: "/accounts/#{su.id}?casestudies=1")
  end
end

So, this is a simple Phoenix update function which handles case study submissions in my app. Now, I’ve tried with:

, do: do_update(conn, params)

and

do do_update(conn, params)

and both throw an error. I either get “unexpected end” at the end of the file or “Syntax error before: do”.

Can someone please explain what I’m doing wrong, because it’s not obvious?

Thanks,
Lee

 ...

  with true <- valid_file_params(params), # start on the same line
     {:ok, file} <- Repo.update(File.changeset(casestudy.file, %{"title" => params["file"].filename, "filename" => make_filename(params)})),
     {:ok, _casestudy} <- Repo.update(Casestudy.changeset(casestudy, %{"title" => params["title"]})) do
   do_update(conn, params)
  else
  ...
 end

Thanks, I’ll give that a go.