Skip to content

Instantly share code, notes, and snippets.

@pkoch
Created September 4, 2017 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkoch/1511a5879d456f909e2a200d8101b063 to your computer and use it in GitHub Desktop.
Save pkoch/1511a5879d456f909e2a200d8101b063 to your computer and use it in GitHub Desktop.
defmodule Api.Competition do
@moduledoc """
TODO: Write.
"""
use Api.Web, :model
alias Ecto.{Changeset}
@valid_attrs ~w(
voting_started_at
voting_ended_at
)a
schema "competition" do
field :voting_started_at, :utc_datetime
field :voting_ended_at, :utc_datetime
end
defp _cant_change(%Changeset{changes: changes, data: data} = changeset, field) do
with {:ok, old} <- Map.get(data, field),
{:ok, new} <- Map.get(changes, field),
old != nil && old != new
do
Changeset.add_error(changeset, field, "can't be changed")
else
_ -> changeset
end
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, @valid_attrs)
|> _cant_change(:voting_started_at)
|> _cant_change(:voting_ended_at)
end
end
defmodule Api.CompetitionActions do
use Api.Web, :action
alias Api.{Competition}
defp _change(params) do
(Repo.one(from(c in Competition)) || %Competition{})
|> Competition.changeset(params)
|> Repo.insert_or_update
end
def open_voting do
_change(%{
voting_started_at: DateTime.utc_now()
})
end
def close_voting do
_change(%{
voting_ended_at: DateTime.utc_now()
})
end
end
defmodule Api.CompetitionActionsTest do
use Api.ModelCase
alias Api.{CompetitionActions}
test "voting_ended_at set" do
{:ok, _} = CompetitionActions.open_voting()
end
test "voting_ended_at set twice" do
{:ok, _} = CompetitionActions.open_voting()
{:error, _} = CompetitionActions.open_voting()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment