Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Check if string is empty

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?

like image 434
ET-CS Avatar asked Dec 18 '22 03:12

ET-CS


1 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
like image 81
Dogbert Avatar answered Dec 28 '22 19:12

Dogbert