Skip to content

Commit

Permalink
Merge pull request #1 from Frameio/attribute_blacklist
Browse files Browse the repository at this point in the history
Add blacklists to cereal
  • Loading branch information
michaeljguarino authored Nov 13, 2017
2 parents 58ba612 + 79b2de5 commit 431ba17
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
14 changes: 10 additions & 4 deletions lib/cereal/builders/entity.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 9 additions & 0 deletions test/cereal/builders/entity_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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"}]
Expand Down

0 comments on commit 431ba17

Please sign in to comment.