Ecto.Repo.Hooks (ecto_hooks v0.1.0) View Source
When use-ed in a module that also use-es Ecto.Repo, augments the following
Ecto.Repo callbacks to provide user definable hooks following successful
execution.
Hooks to MyApp.EctoSchema.after_get/1:
all/2get/3get!/3get_by/3get_by!/3one/2one!/2
Hooks to MyApp.EctoSchema.after_delete/1:
delete/2delete!/2
Hooks to MyApp.EctoSchema.after_insert/1:
insert/2insert!/2
Hooks to MyApp.EctoSchema.after_update/1:
update/2update!/2
Hooks to MyApp.EctoSchema.after_insert/1 or to MyApp.Ecto.Schema.after_update/1:
insert_or_update/2insert_or_update!/2
Please note that the result of executing a hook is the result ultimately returned a user, and thus you should aim to only modify a given database result.
Any results wrapped within an {:ok, _} or {:error, _} are also returned re-wrapped
as expected.
Example usage:
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