Elixir
Last active
July 2, 2017 00:37
-
-
Save yordis/f1749be39e44a4129a2df7436bac7f4b to your computer and use it in GitHub Desktop.
Elixir Utils
This file contains hidden or 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 StrawtHat.Ecto.Changeset do | |
alias Ecto.Changeset | |
def validate_date_range(%Changeset{valid?: true} = changeset, start_field, end_field, opts \\ %{}) do | |
start_at = Changeset.get_field(changeset, start_field) | |
end_at = Changeset.get_field(changeset, end_field) | |
comparison = Map.get(opts, :comparison, :lt) |> datetime_diff_to_timex_diff() | |
if Timex.compare(start_at, end_at) == comparison do | |
changeset | |
else | |
Changeset.add_error(changeset, start_field, message(opts, "is out of range")) | |
end | |
end | |
def validate_date_range(changeset, _, _, _, _), do: changeset | |
defp message(opts, key \\ :message, default) do | |
Keyword.get(opts, key, default) | |
end | |
defp datetime_diff_to_timex_diff(:lt), do: -1 | |
defp datetime_diff_to_timex_diff(:gt), do: 1 | |
defp datetime_diff_to_timex_diff(:eq), do: 0 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment