From c3790a2416827cd56852e9536946183ddd202a6f Mon Sep 17 00:00:00 2001 From: Michael Guarino Date: Mon, 13 Nov 2017 14:57:11 -0500 Subject: [PATCH 1/2] Add blacklists to cereal --- lib/cereal/builders/entity.ex | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/cereal/builders/entity.ex b/lib/cereal/builders/entity.ex index 1d3f7d0..20219e0 100644 --- a/lib/cereal/builders/entity.ex +++ b/lib/cereal/builders/entity.ex @@ -70,15 +70,21 @@ defmodule Cereal.Builders.Entity do defp filter_attributes(attrs, %{serializer: serializer, opts: %{fields: fields}} = context) when is_list(fields) do type = serializer.type(context.data, context.conn) |> String.to_atom() - do_filter_attributes(attrs, fields[type]) + do_filter_attributes(attrs, {:take, fields[type]}) + end + defp filter_attributes(attrs, %{serializer: serializer, opts: %{excludes: fields}} = context) when is_list(fields) do + type = serializer.type(context.data, context.conn) |> String.to_atom() + do_filter_attributes(attrs, {:drop, fields[type]}) end defp filter_attributes(attrs, _), do: attrs defp do_filter_attributes(attrs, nil), do: attrs - defp do_filter_attributes(attrs, fields) when is_list(fields), + defp do_filter_attributes(attrs, {:take, fields}) when is_list(fields), do: Map.take(attrs, fields) - defp do_filter_attributes(attrs, fields) when is_binary(fields) do + defp do_filter_attributes(attrs, {:drop, fields}) when is_list(fields), + do: Map.drop(attrs, fields) + defp do_filter_attributes(attrs, {action, fields}) when is_binary(fields) do fields = fields |> String.split(",") |> Enum.map(&String.to_atom/1) - do_filter_attributes(attrs, fields) + do_filter_attributes(attrs, {action, fields}) end end From 79b2de5de69796205700a90637cd130f79ecac28 Mon Sep 17 00:00:00 2001 From: Michael Guarino Date: Mon, 13 Nov 2017 15:03:12 -0500 Subject: [PATCH 2/2] Add test --- test/cereal/builders/entity_test.exs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test/cereal/builders/entity_test.exs b/test/cereal/builders/entity_test.exs index fe8cb50..2014fc1 100644 --- a/test/cereal/builders/entity_test.exs +++ b/test/cereal/builders/entity_test.exs @@ -112,6 +112,15 @@ defmodule Cereal.Builders.EntityTest do assert Entity.build(context) == expected end + test "it will conditionally drop excluded fields", %{context: context} do + data = %TestModel.User{id: 1, name: "Dummy"} + opts = %{excludes: [user: "name"]} + context = %{context | data: data, serializer: UserSerializer, opts: opts} + expected = %Entity{id: 1, type: "user", attributes: %{not_an_attr: true}} + + assert Entity.build(context) == expected + end + test "it will build a deeply nested entity", %{context: context} do user = %TestModel.User{id: 1, name: "Johnny User"} comments = [%TestModel.Comment{id: 1, user: user, text: "A comment"}]