Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR ELIXIR

elixir with else

defmodule SomeModule do
  require Logger

  @doc """
      iex> SomeModule.do_something("Richard")
      {:ok, "Message sent!"}

      iex> SomeModule.do_something("Jian")
      {:error, "Invalid phone number"}

      iex> SomeModule.do_something("Erlich")
      {:error, "Not found"}
  """
  def do_something(name) do
    with {:ok, phone_number} <- look_up(name),
         :sent <- send_text(phone_number) do
      {:ok, "Message sent!"}
    end
  end

  def do_something_and_log_error(name) do
    with {:ok, phone_number} <- look_up(name),
         :sent <- send_text(phone_number) do
      {:ok, "Message sent!"}
    else
      {:error, error_msg} = error ->
        Logger.error(error_msg)
        error
    end
  end

  defp look_up("Richard"), do: {:ok, "+15629998888"}
  defp look_up("Jian"), do: {:ok, "+864009999999"}
  defp look_up(_), do: {:error, "Not found"}

  defp send_text("+1" <> _phone_number), do: :sent
  defp send_text(_), do: {:error, "Invalid phone number"}
end
 
PREVIOUS NEXT
Tagged: #elixir
ADD COMMENT
Topic
Name
2+3 =