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

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
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
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
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
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
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews