Skip to content

Commit

Permalink
Add @behaviour and update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieuprog committed Mar 31, 2020
1 parent d68a093 commit 8a2f4fc
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
32 changes: 30 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
# VirtualFieldsFiller
# Virtual Fields Filler

Fill the virtual fields for your Ecto structs and nested structs recursively:
Fill the virtual fields for your Ecto structs and nested structs recursively.

In your Schema, add the `fill_virtual_fields/1` function:

```
defmodule MyApp.User do
@behaviour VirtualFieldsFiller
use Ecto.Schema
alias __MODULE__
schema "joggers" do
field(:first_name, :string)
field(:last_name, :string)
field(:full_name, :string, virtual: true)
timestamps(type: :utc_datetime)
end
def fill_virtual_fields(%Jogger{} = jogger) do
first_name = Map.fetch!(jogger, :first_name)
last_name = Map.fetch!(jogger, :last_name)
Map.put(jogger, :full_name, "#{first_name} #{last_name}")
end
end
```

Then, after fetching a user (or list of users) from your DB, call `VirtualFieldsFiller.fill_virtual_fields/1`:

```
import VirtualFieldsFiller
Expand All @@ -10,6 +36,8 @@ User
|> fill_virtual_fields()
```



If you use [QueryBuilder](https://github.com/mathieuprog/query_builder), you may organize your code as follows:


Expand Down
2 changes: 2 additions & 0 deletions lib/virtual_fields_filler.ex
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
defmodule VirtualFieldsFiller do
@callback fill_virtual_fields(struct) :: struct

def fill_virtual_fields([]), do: []

def fill_virtual_fields([head | tail]) do
Expand Down
1 change: 1 addition & 0 deletions test/support/models/jog_record.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ defmodule VirtualFieldsFiller.JogRecord do
use QueryBuilder, assoc_fields: [:jogger]
use Ecto.Schema
alias __MODULE__
@behaviour VirtualFieldsFiller

schema "jog_records" do
field(:time, :integer)
Expand Down
1 change: 1 addition & 0 deletions test/support/models/jogger.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ defmodule VirtualFieldsFiller.Jogger do
use QueryBuilder, assoc_fields: [:team, :jog_records]
use Ecto.Schema
alias __MODULE__
@behaviour VirtualFieldsFiller

schema "joggers" do
field(:first_name, :string)
Expand Down

0 comments on commit 8a2f4fc

Please sign in to comment.