EctoHooks

In the past, Ecto provided automatic callbacks which could be implemented to run before or after certain database operations using the Ecto.Model macro (rather than the modern variant: Ecto.Changeset).

This library provides an a module you can use in your application's MyApp.Repo module: Ecto.Repo.Hooks. Upon invokation, any successful database Ecto.Repo callbacks will trigger any hooks you've defined in a corresponding Ecto.Schema module:

def MyApp.Repo do
  use Ecto.Repo,
    otp_app: :my_app,
    adapter: Ecto.Adapters.Postgres

  use Ecto.Repo.Hooks
end

def MyApp.User do
  use Ecto.Changeset

  schema "users" do
    field :first_name, :string
    field :last_name, :string

    field :full_name, :string, virtual: true
  end

  def after_get(%__MODULE__{first_name: first_name, last_name: last_name} = user) do
    %__MODULE__{user | full_name: first_name <> " " <> last_name}
  end
end

As one can see, this is pretty useful for resolving virtual fields, but can also prove useful for centralising some logging or telemetry logic.

At the time of writing, this library does not intend on implementing any hooks for executing logic before a database operation. The only hooks implemented are those that are executed following an appropriate Ecto.Repo callback.

Installation

You can install this dependency by adding the following to your application's mix.exs:

def deps do
  [
    {:ecto_hooks, "~> 0.1.0"}
  ]
end

Usage

Simply add the following line to your application's corresponding MyApp.Repo module:

use Ecto.Repo.Hooks

Any time an Ecto.Repo callback successfully returns a struct defined in a module that use-es Ecto.Model, any corresponding defined hooks are executed.

All hooks are of arity one, and take only the struct defined in the module as an argument. Hooks are expected to return an updated struct on success, any other value is treated as an error.

A list of valid hooks is listed below: