Created
January 21, 2015 11:12
-
-
Save josevalim/1ed574b388c32f056da1 to your computer and use it in GitHub Desktop.
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 Rocket.DateTime do | |
def type, do: :datetime | |
# Provide our own casting rules. | |
def cast(string) when is_binary(string) do | |
# Try to parse different formats here | |
end | |
# Datetime itself should also be valid | |
def cast(%Ecto.DateTime{} = datetime) do | |
{:ok, datetime} | |
end | |
# Everything else needs to be a failure though | |
def cast(_), do: :error | |
# Datetimes are never considered blank | |
def blank?(_), do: false | |
# When loading data from the database, we need to | |
# convert the Ecto type to our type: | |
def load({{year, month, day}, {hour, min, sec}}) do | |
{:ok, %Ecto.DateTime{year: year, month: month, day: day, | |
hour: hour, min: min, sec: sec}} | |
end | |
# When dumping data to the database, we need to convert | |
# our type back to Ecto.DateTime one: | |
def dump(%Ecto.DateTime{} = dt) do | |
{:ok, {{dt.year, dt.month, dt.day}, {dt.hour, dt.min, dt.sec}}} | |
end | |
def dump(_), do: :error | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment