Skip to content

Instantly share code, notes, and snippets.

@imranismail
Last active January 5, 2017 15:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imranismail/b9ef7741798dbcda727417d033ac694f to your computer and use it in GitHub Desktop.
Save imranismail/b9ef7741798dbcda727417d033ac694f to your computer and use it in GitHub Desktop.
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