Elixir - Check if string is empty

Viewed 5456

I am playing with Elixir and Phoenix Framework for the first time after following this Tutorial..

I have a simple client/server app.

chat/lib/chat_web/room_channel.ex:

defmodule ChatWeb.RoomChannel do
  use Phoenix.Channel

  def join("room:lobby", _message, socket) do
    {:ok, socket}
  end
  def join("room:" <> _private_room_id, _params, _socket) do
    {:error, %{reason: "unauthorized"}}
  end

  def handle_in("new_msg", %{"body" => body}, socket) do
    broadcast! socket, "new_msg", %{body: body}
    {:noreply, socket}
  end
end

I want to block empty incoming messages (body is empty string)

def handle_in("new_msg", %{"body" => body}, socket) do
  # I guess the code should be here..
  broadcast! socket, "new_msg", %{body: body}
  {:noreply, socket}
end

How can I do that?

2 Answers

I want to block empty incoming messages (body is empty string)

You can add a guard clause for this. Either when body != "" or when byte_size(body) > 0

def handle_in("new_msg", %{"body" => body}, socket) when body != "" do
  ...
end

Now this function will only match if body is not "".

If you also want to handle empty body case, you can add two clauses like this (no need for the guard clause anymore since the second clause will never match if body is empty):

def handle_in("new_msg", %{"body" => ""}, socket) do
  # broadcast error here
end
def handle_in("new_msg", %{"body" => body}, socket) do
  # broadcast normal here
end

You can use answer proposed by @Dogbert, but to be 100% sure that string is not empty you can use wrap the broadcast! in the helper private function or just wrap into if or unless (negative if) expression.

unless String.trim(body) == "" do
  broadcast! socket, "new_msg", %{body: body}
end

If you want to return an error message you try to use something more complex eg.:

if String.trim(body) != "" do
  broadcast! socket, "new_msg", %{body: body}
else
  broadcast! socket, "error_msg", %{body: "Body is empty"}
end
Related