Skip to content

Commit

Permalink
Merge pull request #16 from Frameio/give-transform-access-to-conn
Browse files Browse the repository at this point in the history
Allow optional access to conn from transform function
  • Loading branch information
yuvalidan authored May 14, 2020
2 parents 00f3941 + 82cbae1 commit 8833937
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 9 deletions.
2 changes: 1 addition & 1 deletion lib/cereal/builders/entity.ex
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ defmodule Cereal.Builders.Entity do
def build(%{serializer: serializer} = context) do
context =
context
|> Map.put(:data, serializer.transform(context.data))
|> Map.put(:data, serializer.transform(context.data, context.conn))
|> do_assigns()

%__MODULE__{
Expand Down
11 changes: 8 additions & 3 deletions lib/cereal/serializer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ defmodule Cereal.Serializer do
unquote(define_default_attributes())
unquote(define_default_relationships())
unquote(define_default_preload())

def transform(data), do: data
defoverridable [transform: 1]
unquote(define_default_transform())

@before_compile Cereal.Serializer
end
Expand All @@ -60,6 +58,13 @@ defmodule Cereal.Serializer do
end
end

defp define_default_transform do
quote do
def transform(data, _), do: data
defoverridable [transform: 2]
end
end

defp define_default_type(module) do
type_for_module = Utils.module_to_type(module)

Expand Down
10 changes: 5 additions & 5 deletions test/cereal/builders/entity_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ defmodule Cereal.Builders.EntityTest do
defmodule TransformedSerializer do
use Cereal.Serializer
attributes [:name]
def transform(data) do
%{name: data.name <> "-1"}
def transform(data, conn) do
%{name: data.name <> "-1-" <> conn.name}
end
end

Expand Down Expand Up @@ -202,11 +202,11 @@ defmodule Cereal.Builders.EntityTest do
assert Entity.build(context) == expected
end

test "it will modify attributes with a transform function", %{context: context} do
test "it will modify attributes with a transform/2 function", %{context: context} do
user = %TestModel.User{id: 1, name: "Johnny"}
context = %{context | data: user, serializer: TransformedSerializer}
context = %{context | data: user, conn: %{name: "conn-name"}, serializer: TransformedSerializer}

expected = %Entity{attributes: %{name: "Johnny-1"}, type: "transformed"}
expected = %Entity{attributes: %{name: "Johnny-1-conn-name"}, type: "transformed"}

assert Entity.build(context) == expected
end
Expand Down

0 comments on commit 8833937

Please sign in to comment.