mirror of
https://github.com/philomena-dev/philomena.git
synced 2024-12-18 15:08:00 +01:00
114 lines
1.8 KiB
Elixir
114 lines
1.8 KiB
Elixir
defmodule Philomena.Polls do
|
|
@moduledoc """
|
|
The Polls context.
|
|
"""
|
|
|
|
import Ecto.Query, warn: false
|
|
alias Philomena.Repo
|
|
|
|
alias Philomena.Polls.Poll
|
|
|
|
@doc """
|
|
Returns the list of polls.
|
|
|
|
## Examples
|
|
|
|
iex> list_polls()
|
|
[%Poll{}, ...]
|
|
|
|
"""
|
|
def list_polls do
|
|
Repo.all(Poll)
|
|
end
|
|
|
|
@doc """
|
|
Gets a single poll.
|
|
|
|
Raises `Ecto.NoResultsError` if the Poll does not exist.
|
|
|
|
## Examples
|
|
|
|
iex> get_poll!(123)
|
|
%Poll{}
|
|
|
|
iex> get_poll!(456)
|
|
** (Ecto.NoResultsError)
|
|
|
|
"""
|
|
def get_poll!(id), do: Repo.get!(Poll, id)
|
|
|
|
@doc """
|
|
Creates a poll.
|
|
|
|
## Examples
|
|
|
|
iex> create_poll(%{field: value})
|
|
{:ok, %Poll{}}
|
|
|
|
iex> create_poll(%{field: bad_value})
|
|
{:error, %Ecto.Changeset{}}
|
|
|
|
"""
|
|
def create_poll(attrs \\ %{}) do
|
|
%Poll{}
|
|
|> Poll.changeset(attrs)
|
|
|> Repo.insert()
|
|
end
|
|
|
|
@doc """
|
|
Updates a poll.
|
|
|
|
## Examples
|
|
|
|
iex> update_poll(poll, %{field: new_value})
|
|
{:ok, %Poll{}}
|
|
|
|
iex> update_poll(poll, %{field: bad_value})
|
|
{:error, %Ecto.Changeset{}}
|
|
|
|
"""
|
|
def update_poll(%Poll{} = poll, attrs) do
|
|
poll
|
|
|> Poll.changeset(attrs)
|
|
|> Repo.update()
|
|
end
|
|
|
|
@doc """
|
|
Deletes a Poll.
|
|
|
|
## Examples
|
|
|
|
iex> delete_poll(poll)
|
|
{:ok, %Poll{}}
|
|
|
|
iex> delete_poll(poll)
|
|
{:error, %Ecto.Changeset{}}
|
|
|
|
"""
|
|
def delete_poll(%Poll{} = poll) do
|
|
Repo.delete(poll)
|
|
end
|
|
|
|
@doc """
|
|
Returns an `%Ecto.Changeset{}` for tracking poll changes.
|
|
|
|
## Examples
|
|
|
|
iex> change_poll(poll)
|
|
%Ecto.Changeset{source: %Poll{}}
|
|
|
|
"""
|
|
def change_poll(%Poll{} = poll) do
|
|
Poll.changeset(poll, %{})
|
|
end
|
|
|
|
def active?(%{id: poll_id}) do
|
|
now = DateTime.utc_now()
|
|
|
|
Poll
|
|
|> where([p], p.id == ^poll_id and p.active_until > ^now)
|
|
|> Repo.exists?()
|
|
end
|
|
|
|
def active?(_poll), do: false
|
|
end
|