Skip to content

Instantly share code, notes, and snippets.

@ponty96
Created June 3, 2017 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ponty96/abf8d6b5310b101bfd52239d9bf60767 to your computer and use it in GitHub Desktop.
Save ponty96/abf8d6b5310b101bfd52239d9bf60767 to your computer and use it in GitHub Desktop.
Parser for Ecto Changeset Errors
defmodule Ponty96.ToolTips.ErrorParser do
import Ponty96.ToolTips.Camelize, only: [camelize: 1]
def parse_errors(changeset) do
errors =
changeset
|> handle_changeset_errors()
|> Map.to_list
|> Enum.map(fn error ->
key = error |> elem(0) |> Atom.to_string |> camelize()
[val] = elem(error, 1)
%{key: key, message: val}
end)
errors
end
defp handle_changeset_errors(changeset) do
errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, opts} ->
Enum.reduce(opts, msg, fn {key, value}, _acc ->
String.replace(msg, "%{#{key}}", to_string(value))
end)
end)
errors
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment