artem

artem

Hi all

I am still in my early days with Elixir and relatively new to functional languages (did one hobby project in Elm), so most interested in figuring the elixir ways for this or that.

Quite often I am in the situation where I need to have a look at the function input and do an early exit, yet an input validation is something beyond what simple pattern matching or guard could do - a function needs to be called.

For example, in my weather forecast live view there is a handle_event that should only go fetch weather if user has chosen a date already. Otherwise, we just do nothing:

 def handle_event("fetch-weather", _, socket) do
  weatherRow = if (socket.assigns[:target_date] == nil) do
    []
  else
    # actually fill weatherRow with some sensible info
  end
  socket = assign(socket,
      :weatherRow, weatherRow
  )
  {:noreply, socket}
 end

All these argument validation feel to not nice in elixir, but I can’t really think of a good solution.
The best I could think of is about making an original function just extract the data to be validated:

def handle_event("fetch-weather", _, socket) do
  target_date = socket.assigns[:target_date]
  weatherRow = target_date |> handle_fetch_weather_inner
  socket = assign(socket,
       :weatherRow, weatherRow
   )
   {:noreply, socket}
end

defp handle_fetch_weather_inner(nil)
  []
end

defp handle_fetch_weather_inner(nonEmptyTargetDate)
  # Fetch weather using the target date
end

How would you do something like this?
Am I missing some way to pattern match or put guard on the original handle_event?

Showing Posts 1 to 4

stefanluptak

stefanluptak

Hi @artem, welcome to the forum. :slight_smile:

I sometimes want a simple return ... call too. I was used to having that in in Swift.

Anyway, here’s a gist I made with a few approaches. Somebody will come up with an even more clever one, I guess. But hopefully, this would be useful for you.

If you have a LiveBook, you can open that file and play with it more.

al2o3cr

al2o3cr

IMO @stefanluptak’s first approach (top-level if with return values in each branch) is pretty standard.

Alternatively, consider interlocking the code so that whatever is sending fetch-weather can’t happen without target_date being in the assigns.

ityonemo

ityonemo

Totally different way:

new_blabla = socket.assigns[:blabla]
|> List.wrap
|> do_the_thing_its_always_a_list

Note List.wrap gives [] on nil. It’s a secret power weapon in elixir.

List.wrap(if something = x.y do: process(something))

is also a common pattern in my toolbelt

artem

artem OP

Thank you guys, I didn’t realize I could pattern match on map inside a map as

def handle_event3(
        "fetch-weather",
        _params,
        %{assigns: %{target_date: target_date}} = socket
      )

I guess most proper approach is what @stefanluptak posted as handle_event1, for now I’ll try some more function header matching to learn it more. It probably wouldn’t work if I needed some checks with function calls (e.g. validate_date(target_date)), but for my current needs matching works well.

I figured I can even check for the existence of a key as well as in

 def handle_event("fetch-weather", _, %{assigns: assigns} = socket) when not is_map_key(assigns, :target_date) do
    Logger.info("target_date key is missing")
    {:noreply, socket}
  end

  def handle_event("fetch-weather", _, %{assigns: %{target_date: nil}} = socket) do
    Logger.info("handle_event: target_date is nil")
    {:noreply, socket}
  end

  def handle_event("fetch-weather", _, %{assigns: %{target_date: target_date}} = socket) do
    Logger.info("Going to fetch weather")
    ...
  end
— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews