Skip to content

Instantly share code, notes, and snippets.

@mxgrn
Last active April 6, 2024 19:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
@dsincl12
Copy link

dsincl12 commented Apr 5, 2024

no update? :)

@mxgrn
Copy link
Author

mxgrn commented Apr 6, 2024

no update? :)

It was just a POC to start a discussion, I expect more functions than just update to go here.

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