Skip to content

Instantly share code, notes, and snippets.

@imranismail

imranismail/README.md

Last active Jan 5, 2017
Embed
What would you like to do?
Implementing Ruby's lonely operator using Elixir's custom infix function

Implementing Ruby's lonely operator using Elixir's custom infix function

iex> import ViewHelper
iex> user = %{name: "Imran", address: %{postcode: 33160}}
iex> user ~> :name
# "Imran"
iex> user ~> :address ~> :postcode
# 33160
iex> user ~> :address ~> :country
# nil

Update

Just found out from benwilson that [] implements the access protocol, so it would return nil even when accessing from nil.

Using access:

iex> user = %{name: "imran"}
iex> user[:name][:address][:postcode]
# nil

OR if you want the same syntax as above
iex> user |> Access.get(:name) |> Access.get(:postcode)
# nil

OR use get_in DUH!

Rewrote to just use the Access module

Update 2

Use back old implementation because Access protocol is not implemented on struct unless explicitly derived. Rightly so.

defmodule ViewHelper do
def left ~> right do
try_in(left, right)
end
defp try_in(nil, _keys), do: nil
defp try_in(result, []), do: result
defp try_in(struct, [head|tail]), do: try_in(Map.get(struct, head), tail)
defp try_in(struct, key), do: Map.get(struct, key)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment