sudostack

sudostack

Having written a lot more Phoenix templates as of late, I’m doing a lot more attribute checks than I would like. In Ruby 2.3 we could use the #try method or the safe-navigation operator &. to navigate possible nested nils. Here, if address was nil, then it shouldn’t try to access city:

Ruby:
user.try(:address).try(:city) OR user&.address&.city as opposed to user && user.address && user.address.city / writing nested if expressions/statements.

Is there a nicer way to navigate nested maps or structs in Elixir, so that code that I write in EEX could be more terse? Or is there a better pattern to not have an exception raised if I’m trying to access a nested field found in a parent field that is nil?

Showing Posts 1 to 10

net

net

user[:address][:city]

# or

user.address[:city]

I don’t know what your use case is, but an if might be more idiomatic and expressive. Otherwise, you can use one of the above.

sudostack

sudostack OP

Oh, right! I forgot and I could also use Kernel.get_in/2

sudostack

sudostack OP

I spoke too soon as both your examples would raise an UndefinedFunctionError returning User does not implement the Access Behaviour.

However, I believe the current best alternative is: user |> Map.get(:address) |> Map.get(:city), but if I import Map, only: [:get], then it becomes user |> get(:address) |> get(:city)

net

net

You can add @derive [Access] to your User and Address struct/schema modules to fix this.

However, I would recommend defining a named function to accomplish your needs instead.

defmodule User do
  def city(%{address: nil}), do: nil
  def city(%{address: address}), do: address.city
end
sudostack

sudostack OP

Doesn’t work either: (ArgumentError) Access is not a protocol, cannot derive Access for User. However, I agree that it’s probably better to use a named function and likely the more idiomatic solution I’m looking for…

net

net

Whoops, sorry. Looks like that was changed long ago.

sudostack

sudostack OP

Hmm. I probably should’ve searched earlier, but @danielberkompas asked this last year: Maybe: nil protection for nested structs - #7 by Qqwy and he even created a small module that is a nod to the Maybe monad in Haskell?

sudostack

sudostack OP

Additional context for why deriving Access doesn’t work: Get rid of the Access protocol · Issue #2973 · elixir-lang/elixir · GitHub

OvermindDL1

OvermindDL1

If you want something library-less and simple then you could just use with:

iex(46)> blah = %{vwoop: nil}
%{vwoop: nil}
iex(47)> with\
...(47)>   %{vwoop: vwoop} <- blah,
...(47)>   %{vreep: vreep} <- vwoop do
...(47)>   vreep+4
...(47)> else nil end
nil

An aside:
I really wish with was just a macro and not a special form and that it put everything in the do like:

with do
  %{vwoop: vwoop} <- blah
  %{vreep: vreep} <- vwoop
  vroop when vroop > 12 <- vreep + 4
  {:ok, vroop}
else
  :error
end

It would be so much easier to use with no weird spacing stuff and trailing comma’s that is inconsistent with most matcher cases and such… >.>

Consequently there is a fixed version in a library. :wink:

sudostack

sudostack OP

Yeah, I actually first thought about using with special form but it’s too verbose for me, especially in template code.

Ah, yes! I wish it were a macro, too. Has this suggestion ever been brought up in the mailing list?

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
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
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
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
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

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
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews