Current section

Files

Jump to
ex_trello lib ex_trello utils.ex
Raw

lib/ex_trello/utils.ex

defmodule ExTrello.Utils do
@moduledoc """
A collection of helpful utility functions.
"""
@doc """
Will parse over any JSON response from the Trello API & snake case any camelCased keys (also convert them to atoms)
Example
body = %{"dateLastActivity" => %{ "potatoSkins" => "asdf", "somethingElse" => %{ "heyThere" => "sup"}}, "rootMap" => "right here", "someList" => [%{"keysInHere" => "too"}, %{"cantBelieve" => %{"thisIsHappening" => "it is tho"}}]}
iex> ExTrello.Utils.snake_case_keys body
%{date_last_activity: %{potato_skins: "asdf",
something_else: %{hey_there: "sup"}}, root_map: "right here",
some_list: [%{keys_in_here: "too"},
%{cant_believe: %{this_is_happening: "it is tho"}}]}
"""
def snake_case_keys(map) when is_map(map) do
Enum.reduce(map, %{}, fn
{key, value}, acc when is_map(value) ->
Map.put(acc, Macro.underscore(key) |> attempt_atom_conversion, snake_case_keys(value))
{key, value}, acc when is_list(value) ->
Map.put(acc, Macro.underscore(key) |> attempt_atom_conversion, Enum.map(value, &snake_case_keys/1))
{key, value}, acc ->
Map.put(acc, Macro.underscore(key) |> attempt_atom_conversion, value)
end)
end
def snake_case_keys(object) when is_list(object) do
Enum.map(object, &snake_case_keys/1)
end
def snake_case_keys(object), do: object
# Let's keep things nice and atom-y
defp attempt_atom_conversion(string) do
try do
String.to_existing_atom(string)
rescue
ArgumentError -> String.to_atom(string)
end
end
end