Last active
February 6, 2022 06:19
-
-
Save MeerKatDev/b3cbc30ac0d9256045efe364f5c7934e to your computer and use it in GitHub Desktop.
An Elixir model for basic db functionality, to be brief.
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 RichModel do | |
@moduledoc """ | |
A mini-package that injects basic db functionality in any model. | |
Good for rapid prototyping. | |
""" | |
defmacro __using__([]) do # alternatively, `defmacro __using__([repo: repo]) do ....` | |
quote do | |
alias __BASE_MODULE__.Repo # __BASE_MODULE__ is the app root name | |
def get(id, _preload \\ true), do: Repo.get(__MODULE__, id) | |
def get!(id), do: Repo.get!(__MODULE__, id) | |
def list(), do: Repo.all(__MODULE__) | |
def count(), do: Repo.aggregate(__MODULE__, :count, :id) | |
def get_by(opts), do: Repo.get_by(__MODULE__, opts) | |
def get_by!(opts), do: Repo.get_by!(__MODULE__, opts) | |
def create(attrs) do | |
%__MODULE__{} | |
|> __MODULE__.changeset(attrs) | |
|> Repo.insert() | |
end | |
def create!(attrs) do | |
%__MODULE__{} | |
|> __MODULE__.changeset(attrs) | |
|> Repo.insert!() | |
end | |
def update(item = %__MODULE__{}, attrs) do | |
item | |
|> __MODULE__.changeset(attrs) | |
|> Repo.update() | |
end | |
def update!(item = %__MODULE__{}, attrs) do | |
item | |
|> __MODULE__.changeset(attrs) | |
|> Repo.update!() | |
end | |
defoverridable get: 2, list: 0, create: 1, create!: 1, update: 2, update!: 2 | |
import Ecto.Query | |
def list_all_by(field_name, value) do | |
from(t in __MODULE__, where: field(t, ^field_name) == ^value) | |
|> Repo.all() | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment