Last active
June 5, 2017 20:47
-
-
Save sikanhe/9d9b8cfdae0a32df22ff86613a583886 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
defmodule Operations do | |
@moduledoc """ | |
Examples: | |
operations Schema.Trip, :trip | |
operations Schema.User, :user, only: [:get, :delete] | |
# supports :plural option for list_x function | |
operations Schema.Datum, :datum, plural: :data | |
""" | |
defmacro operations(schema, name) do | |
quote do | |
operations(unquote(schema), unquote(name), []) | |
end | |
end | |
defmacro operations(schema, name, opts) do | |
quote location: :keep do | |
ops = Keyword.get(unquote(opts), :only, [:list, :get, :delete]) | |
if :list in ops do | |
def unquote(:"list_#{Keyword.get(opts, :plural, :"#{name}s")}")() do | |
Repo.all(unquote(schema)) | |
end | |
end | |
if :get in ops do | |
def unquote(:"get_#{name}")(id) do | |
Repo.get(unquote(schema), id) | |
end | |
def unquote(:"get_#{name}!")(id) do | |
Repo.get!(unquote(schema), id) | |
end | |
end | |
if :delete in ops do | |
def unquote(:"delete_#{name}")(id) do | |
unquote(schema) | |
|> Repo.get!(unquote(schema), id) | |
|> Repo.delete | |
end | |
def unquote(:"delete_#{name}!")(id) do | |
unquote(schema) | |
|> Repo.get!(unquote(schema), id) | |
|> Repo.delete! | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment