Last active
May 16, 2024 09:22
-
-
Save mxgrn/a8998309b6573dcfbda66d0425ede1bd to your computer and use it in GitHub Desktop.
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
# It's only a POC for now | |
defmodule ContextBase do | |
@moduledoc """ | |
Abstracts away common schema functions, such as list, get, create, update, delete, etc. | |
Assumes that the schema module has a `changeset` function. | |
Usage: | |
defmodule MyContext do | |
use ContextBase, repo: MyApp.Repo, schema: MyApp.MySchema | |
end | |
Options: | |
- :repo: the repo module to use | |
- :schema: the schema module to use | |
""" | |
defmacro __using__(opts) do | |
repo = Module.concat([Keyword.get(opts, :repo) |> Macro.to_string()]) | |
schema = Module.concat([Keyword.get(opts, :schema) |> Macro.to_string()]) | |
quote do | |
def list() do | |
unquote(repo).all(unquote(schema)) | |
end | |
def get(id) do | |
unquote(repo).get(unquote(schema), id) | |
end | |
def create(attrs) do | |
%unquote(schema){} | |
|> unquote(schema).changeset(attrs) | |
|> unquote(repo).insert() | |
end | |
def delete(record) do | |
unquote(repo).delete(record) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
there's a typo for the get function @mxgrn 😉
and for the update @dsincl12 do not unquote otherwise you'll get an error because ecto is waiting for the same struct as the unquoted schema if i'm not mistaking