Created
June 3, 2017 22:20
-
-
Save ponty96/abf8d6b5310b101bfd52239d9bf60767 to your computer and use it in GitHub Desktop.
Parser for Ecto Changeset Errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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