Hi everyone,
Decoratex is my first Elixir package. It’s a very simple package but it helped me and my team to organize some logic of our project.
It provides methods to add virtual fields in Ecto models and it loads data into them when needed, keeping the Ecto model structure. It’s meant to be used for fields that can’t be calculated with just DB queries.
In this article, we explain our motivation in depth.
Here is an example of use:
defmodule User do
use Ecto.Schema
use Decoratex
decorations do
decorate_field :ability, :string, &UserHelper.get_ability/1
decorate_field :absences, :integer, &UserHelper.count_absences/1
...
end
schema "users" do
has_many :periods, Period, on_delete: :delete_all
belongs_to :setting, Setting
field :email, :string
...
add_decorations
end
end
Then, you can load data into fields with decorate
:
user = User
|> Repo.get(1)
|> Repo.preload(:settings)
|> Repo.preload(:periods)
|> User.decorate
%User{email: …, ability: :manager, absences: 10}
# or User.decorate(:ability)
# or User.decorate([:absences, :ability])
And use the %User{} struct with extra data as you wish, for example in patttern matching, views, json…
As my frist package, I will appreciate any comments or suggestions
In upcoming versions, I will try to add some improvements like sending custom params to the decoration functions.
Thank you!