Skip to content

Commit

Permalink
Cleanup ecto type documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
maennchen committed Oct 23, 2024
1 parent 7265493 commit 3120b84
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions lib/crontab/cron_expression/ecto_type.ex
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ if match?({:module, Ecto.Type}, Code.ensure_compiled(Ecto.Type)) do
field :schedule, Crontab.CronExpression.Ecto.Type
end
## Casted Values
It is recommended to only pass `Crontab.CronExpression` structs to the
field.
The type will automatically cast the string representation to a
`Crontab.CronExpression` struct. This will however only work for normal
(not extended) expressions since the string representation of extended
expressions can't be disambiguated from normal expressions.
"""

alias Crontab.CronExpression
Expand All @@ -25,21 +35,13 @@ if match?({:module, Ecto.Type}, Code.ensure_compiled(Ecto.Type)) do

@behaviour Ecto.Type

@type map_expression :: %{
extended: boolean,
reboot: boolean,
second: [CronExpression.value(Calendar.second())],
minute: [CronExpression.value(Calendar.minute())],
hour: [CronExpression.value(Calendar.second())],
day: [CronExpression.value(Calendar.day())],
month: [CronExpression.value(Calendar.month())],
weekday: [CronExpression.value(Calendar.day_of_week())],
year: [CronExpression.value(Calendar.year())]
}

@doc false
@impl Ecto.Type
@spec type :: :map
def type, do: :map

@doc false
@impl Ecto.Type
@spec cast(any) :: {:ok, CronExpression.t()} | :error
def cast(cron_expression = %Crontab.CronExpression{}), do: {:ok, cron_expression}

Expand All @@ -55,6 +57,8 @@ if match?({:module, Ecto.Type}, Code.ensure_compiled(Ecto.Type)) do

def cast(_), do: :error

@doc false
@impl Ecto.Type
@spec load(any) :: {:ok, CronExpression.t()} | :error
def load(%{"extended" => extended, "expression" => expression}) do
load(%{extended: extended, expression: expression})
Expand All @@ -69,15 +73,23 @@ if match?({:module, Ecto.Type}, Code.ensure_compiled(Ecto.Type)) do

def load(_), do: :error

@doc false
@impl Ecto.Type
@spec dump(any) :: {:ok, CronExpression.t()} | :error
def dump(cron_expression = %CronExpression{extended: extended}) do
{:ok, %{extended: extended, expression: Composer.compose(cron_expression)}}
end

@doc false
@impl Ecto.Type
def dump(_), do: :error

@doc false
@impl Ecto.Type
def embed_as(_), do: :dump

@doc false
@impl Ecto.Type
def equal?(term1, term2), do: term1 == term2
end
end

0 comments on commit 3120b84

Please sign in to comment.