Telepath (Telepath v0.1.3) View Source

Provide an easy way to access elixir's data struct with a path.

Inspired by JsonPath & xPath (for json and xml), Telepath allows you to reach the data that you want, simply by specifying a path.

The path can be created using the sigil: ~t (see Telepath.sigil_t/2).

Link to this section Summary

Functions

Obtains a data at a given path.

Transform the struct path to an array that defines how to access the data.

Link to this section Types

Specs

path() :: [String.t() | atom() | number()]

Link to this section Functions

Link to this function

get(data, path, opts \\ [])

View Source

Obtains a data at a given path.

Telepath.get(%{hello: "world"}, ~t/hello/a)
# "world"

Telepath.get(%{foo: [%{bar: "bar1"}, %{bar: "bar2"}]}, ~t/foo.bar/a)
# ["bar1", "bar2"]

# works also with string key
Telepath.get(%{"foo" => [%{"bar" => "bar1"}, %{"bar" => "bar2"}]}, ~t/foo.bar/)
# ["bar1", "bar2"]

Telepath.get(%{foo: [%{bar: "bar1"}, %{bar: "bar2"}]}, ~t/foo/a)
# [%{bar: "bar1"}, %{bar: "bar2"}]

Telepath.get(%{foo: [%{bar: "bar1"}, %{bar: "bar2"}]}, ~t/*/a)
# [%{bar: "bar1"}, %{bar: "bar2"}]

If you want to map every case in the path, you can use :*.

e.g.

Telepath.get(
  %{data: %{key1: "value1", key2: "value2"}},
  ~t/data.*/a
)
# ["value1", "value2"]

See sigil_t/2 for more informations on path.

opts

  • flatten Return a flattened list (works only if the result of telepath is a list) (default false).
Link to this function

sigil_t(string, opts \\ [])

View Source

Specs

sigil_t(String.t(), List.t()) :: path()

Transform the struct path to an array that defines how to access the data.

Use ~t instead of &Telepath.sigil_t/2.

Modifiers

The modifiers available when creating a Telepath are:

  • atom (a) - enable atom keys for path exploration.

Special characters

Examples

iex> Telepath.sigil_t("node")
["node"]

iex> Telepath.sigil_t("node.attr1")
["node", "attr1"]

iex> Telepath.sigil_t("node[0]")
["node", 0]

iex> Telepath.sigil_t("node[0].attr1")
["node", 0, "attr1"]

iex> Telepath.sigil_t("node.0.attr1")
["node", "0", "attr1"]

iex> Telepath.sigil_t("node.*.attr1")
["node", :*, "attr1"]

With the sigil ~t it will be as simple as:

~t/data/
# ["data"]

~t/data/a
# [:data]