Skip to content

Commit

Permalink
fix: remove derived attributes in the dump function
Browse files Browse the repository at this point in the history
  • Loading branch information
zookzook committed Nov 13, 2022
1 parent e7f2d44 commit c1b60b4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/mongo/collection.ex
Original file line number Diff line number Diff line change
Expand Up @@ -689,11 +689,13 @@ defmodule Mongo.Collection do
quote unquote: false do
attrs_mapping =
@attributes
|> Enum.reject(fn {name, _opts} -> Enum.member?(@derived, name) end)
|> Enum.map(fn {name, opts} -> {name, opts[:name]} end)
|> Enum.map(fn {name, {_, src_name}} -> {name, src_name} end)

embeds_mapping =
(@embed_ones ++ @embed_manys)
|> Enum.reject(fn {name, _mod, _opts} -> Enum.member?(@derived, name) end)
|> Enum.filter(fn {_name, mod, _opts} -> Collection.has_load_function?(mod) end)
|> Enum.map(fn {name, mod, opts} -> {name, mod, opts[:name]} end)
|> Enum.map(fn {name, mod, {_, src_name}} -> {mod, name, src_name} end)
Expand Down
42 changes: 42 additions & 0 deletions test/collections/simple_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,33 @@ defmodule Collections.SimpleTest do
{:ok, [pid: pid]}
end

defmodule Task do
use Collection

collection "tasks" do
attribute :name, String.t(), default: "Fix errors"
attribute :status, integer(), derived: true
after_load &Task.after_load/1
end

def after_load(task) do
%Task{task | status: :loaded}
end

def insert_one(task, top) do
with map <- dump(task),
{:ok, _} <- Mongo.insert_one(top, @collection, map) do
:ok
end
end

def find_one(id, top) do
top
|> Mongo.find_one(@collection, %{@id => id})
|> load()
end
end

defmodule Label do
use Collection

Expand Down Expand Up @@ -89,6 +116,21 @@ defmodule Collections.SimpleTest do
assert %Card{intro: "new intro", label: %Label{color: :red, name: "warning"}} = struct_card
end

test "dump derived attributes", c do
alias Collections.SimpleTest.Task
task = %Task{Task.new() | status: :red}
assert Map.has_key?(Task.dump(task), "status") == false

assert :ok = Task.insert_one(task, c.pid)

task = Task.find_one(task._id, c.pid)

assert %Task{status: :loaded} = task

task = Mongo.find_one(c.pid, "tasks", %{_id: task._id})
assert Map.has_key?(task, "status") == false
end

test "save and find", c do
alias Collections.SimpleTest.Card
alias Collections.SimpleTest.Label
Expand Down

0 comments on commit c1b60b4

Please sign in to comment.