chan11347

chan11347

How to put a if else in a function

i want to add a condition in the add_entry to limit the input such like if else in java, any help

server.ex

def add_entry(todo_server, new_entry) do
    GenServer.cast(todo_server, {:add_entry, new_entry})
  end
@impl GenServer
  def handle_cast({:add_entry, new_entry}, {name, todo_list}) do
    new_list = Todo.List.add_entry(todo_list, new_entry)
    Todo.Database.store(name, new_list)
    {:noreply, {name, new_list}}
  end

list.ex

def add_entry(todo_list, entry) do
    entry = Map.put(entry, :id, todo_list.auto_id)
    new_entries = Map.put(todo_list.entries, todo_list.auto_id, entry)

    %Todo.List{todo_list | entries: new_entries, auto_id: todo_list.auto_id + 1}
  end

Marked As Solved

lucaong

lucaong

If your map contains keys like :date, :time, etc., then your code above won’t work (because it matches an entry with key :entries).

There are a few possible ways to solve this. First, you could check if any of the entry fields is blank. Remember that maps are Enumerable, so you can enumerate them as a collection of {key, value} with the Enum module:

def add_entry(todo_server, new_entry) do
  if Enum.any?(new_entry, fn {_key, value} -> value == nil || value == "" end) do
    IO.puts("input cannot be empty!")
  else
    GenServer.cast(todo_server, {:add_entry, new_entry})
  end
end

Instead of printing an output though, it would be better to return an error, so the caller can pattern match easily. Usually, one would return :ok or {:error, reason}:

def add_entry(todo_server, new_entry) do
  if Enum.any?(new_entry, fn {_key, value} -> value == nil || value == "" end) do
    {:error, "input cannot be empty!"}
  else
    GenServer.cast(todo_server, {:add_entry, new_entry})
  end
end

If the entries always have the same keys, there is a possibly better way to do this: you can use a struct for the entry, instead of a map, to enforce the “shape” of the entry:

defmodule Todo.Server do
  defmodule Entry do
    @enforce_keys [:date, :time, :title]
    defstruct [:date, :time, :title]
  end

  def add_entry(todo_server, %Entry{date: date, time: time, title: title})
  when is_nil(date) or is_nil(time) or is_nil(title) or title == "" do
    {:error, "input cannot be empty!"}
  end

  def add_entry(todo_server, new_entry = %Entry{}) do
    GenServer.cast(todo_server, {:add_entry, new_entry})
  end

  def add_entry(_server, _entry), do: {:error, "Invalid input"}
end

This way, the entry is now a struct that enforces that all of :date, :time, and :value are present. This also mean, though, that the caller of the add_entry function has to pass an Entry struct instead of a map, so it’s your choice whether this is desirable or not.

P.S.:
Unrelated to your question, but you might want to use GenServer.call/3 instead of GenServer.cast/2, even if you don’t need a result. The reason is explained here: https://elixir-lang.org/getting-started/mix-otp/genserver.html#call-cast-or-info

Also Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Please always supply errors and code as text. The images are not readable on my screen, and it makes it very hard to suggest edits because I have to retype everything.

lucaong

lucaong

Yes, now the struct enforces the presence of all the keys. That’s good, because it enforces that an %Entry{} struct without the necessary options simply cannot be created.

That said, if you don’t want that, you can change the struct definition to:

defmodule Entry do
  # remove @enforce_keys
  defstruct date: nil, time: nil, title: nil
end

Make sure you understand the implications first though:

  • If you use a struct enforcing the keys, you enforce the presence of the keys whenever that struct gets created. That’s generally better, because it’s the developer’s job to make sure that the struct is created with the correct keys. In other words, it’s not a runtime concern. You still validate that the supplied values are not nil, because those values might come from user input, so that is a runtime concern, and you might need to give meaningful error messages to the user.

  • If you do not enforce the keys, when those keys are not set they will default to nil, and your code will return an error tuple like {:error, "input cannot be empty!"}. This might sound useful, but if it’s the code that builds the struct wrong, an error message to the user won’t be useful.

Last Post!

chan11347

chan11347

sorry about that i will edit it right now

Where Next?

Popular in Questions Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

Other popular topics Top

baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement