time_unit.ex (2203B)
1 # Zenflows is designed to implement the Valueflows vocabulary, 2 # written and maintained by srfsh <info@dyne.org>. 3 # Copyright (C) 2021-2023 Dyne.org foundation <foundation@dyne.org>. 4 # 5 # This program is free software: you can redistribute it and/or modify 6 # it under the terms of the GNU Affero General Public License as published by 7 # the Free Software Foundation, either version 3 of the License, or 8 # (at your option) any later version. 9 # 10 # This program is distributed in the hope that it will be useful, 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 # GNU Affero General Public License for more details. 14 # 15 # You should have received a copy of the GNU Affero General Public License 16 # along with this program. If not, see <https://www.gnu.org/licenses/>. 17 18 defmodule Zenflows.VF.TimeUnit do 19 @moduledoc """ 20 Custom Ecto type for TimeUnit definitions in schemas. 21 """ 22 use Ecto.Type 23 24 @type t() :: :year | :month | :week | :day | :hour | :minute | :second 25 26 @spec values() :: [t(), ...] 27 def values(), do: ~w[year month week day hour minute second]a 28 29 @impl true 30 def type(), do: :string 31 32 @impl true 33 def cast(:year = x), do: {:ok, x} 34 def cast(:month = x), do: {:ok, x} 35 def cast(:week = x), do: {:ok, x} 36 def cast(:day = x), do: {:ok, x} 37 def cast(:hour = x), do: {:ok, x} 38 def cast(:minute = x), do: {:ok, x} 39 def cast(:second = x), do: {:ok, x} 40 def cast(x), do: {:error, message: "unknown time unit #{inspect(x)}"} 41 42 @impl true 43 def dump(:year), do: {:ok, "year"} 44 def dump(:month), do: {:ok, "month"} 45 def dump(:week), do: {:ok, "week"} 46 def dump(:day), do: {:ok, "day"} 47 def dump(:hour), do: {:ok, "hour"} 48 def dump(:minute), do: {:ok, "minute"} 49 def dump(:second), do: {:ok, "second"} 50 def dump(x), do: {:error, message: "couldn't dump time unit #{inspect(x)}"} 51 52 @impl true 53 def load("year"), do: {:ok, :year} 54 def load("month"), do: {:ok, :month} 55 def load("week"), do: {:ok, :week} 56 def load("day"), do: {:ok, :day} 57 def load("hour"), do: {:ok, :hour} 58 def load("minute"), do: {:ok, :minute} 59 def load("second"), do: {:ok, :second} 60 def load(x), do: {:error, message: "couldn't load time unit #{inspect(x)}"} 61 end