Skip to content

Instantly share code, notes, and snippets.

@sheharyarn
Last active September 24, 2016 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sheharyarn/80d40675f7d5942821d69a95e55136aa to your computer and use it in GitHub Desktop.
Save sheharyarn/80d40675f7d5942821d69a95e55136aa to your computer and use it in GitHub Desktop.
Ecto Shortcuts

Ecto Shortcuts

Intended Usage

Just put use Ecto.Shortcuts in your Ecto model or call it in the model method in the web/web.ex of your Phoenix app.

defmodule PhoenixApp.User do
  use PhoenixApp.Web, :model
  use Ecto.Shortcuts
end

You can now call get/1, all/0, delete/1, etc on the model directly:

User.all
# instead of PhoenixApp.Repo.all(User)

User.get(2)
# instead of PhoenixApp.Repo.get(User, 2)

Concerns

  1. Is the naming scheme correct? (i.e. is Ecto.Shortcuts a good name?)
  2. Is doing this a good idea?
  3. Are there any anti-patterns in the code?
  4. Am I using macros correctly?
  5. What should I keep in mind while publishing this as a hex package?
defmodule Ecto.Shortcuts do
defmacro __using__(_) do
quote do
def all do
apply(kin_module("Repo"), :all, [__MODULE__])
end
def get(id) do
apply(kin_module("Repo"), :get, [__MODULE__, id])
end
## Other methods
## ...
defp parent_module do
__MODULE__
|> Module.split
|> Enum.drop(-1)
|> Module.concat
end
defp kin_module(name) do
Module.concat(parent_module, name)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment