Skip to content

Instantly share code, notes, and snippets.

@mxgrn
Last active May 16, 2024 09:22
Show Gist options
  • Save mxgrn/a8998309b6573dcfbda66d0425ede1bd to your computer and use it in GitHub Desktop.
Save mxgrn/a8998309b6573dcfbda66d0425ede1bd to your computer and use it in GitHub Desktop.
# 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
@Rooarii
Copy link

Rooarii commented May 5, 2024

there's a typo for the get function @mxgrn 😉

  def get!(id) do
    unquote(repo).get!(unquote(schema), id)
  end

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

  def update(schema, attrs) do
        schema
        |> unquote(schema).changeset(attrs)
        |> unquote(repo).update()
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment