Skip to content

Commit

Permalink
Merge pull request #2 from Frameio/lazy_attributes
Browse files Browse the repository at this point in the history
Lazy attribute instantiation
  • Loading branch information
michaeljguarino authored Nov 14, 2017
2 parents 431ba17 + c8193e5 commit 1ac0c6c
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 14 deletions.
4 changes: 3 additions & 1 deletion lib/cereal/builders/entity.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ defmodule Cereal.Builders.Entity do

defp attributes(%{serializer: serializer} = context) do
serializer.attributes(context.data, context.conn)
|> Enum.map(fn {key, fnc} -> {key, fnc.(context.data, context.conn)} end)
|> Enum.into(%{})
|> filter_attributes(context)
end

Expand Down Expand Up @@ -48,7 +50,7 @@ defmodule Cereal.Builders.Entity do

defp build_relation_entity(nil, _, _, _), do: nil
defp build_relation_entity(relation, context, name, rel_opts) do
context
context
|> Map.put(:serializer, rel_opts.serializer)
|> Map.put(:opts, with_relationship_includes(context.opts, name))
|> Map.put(:data, relation)
Expand Down
15 changes: 2 additions & 13 deletions lib/cereal/serializer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ defmodule Cereal.Serializer do
quote do
def attributes(struct, conn) do
__MODULE__.__attributes()
|> Enum.map(&({&1, apply(__MODULE__, &1, [struct, conn])}))
|> Enum.map(& {&1, fn struct, conn -> apply(__MODULE__, &1, [struct, conn]) end})
|> Enum.into(%{})
end
defoverridable [attributes: 2]
Expand Down Expand Up @@ -100,18 +100,7 @@ defmodule Cereal.Serializer do
@attributes @attributes ++ attrs

for attr <- attrs do
has_function? = :erlang.function_exported(__MODULE__, attr, 2)

def unquote(attr)(m, c) do
# For each attribute, see if there is a function exported on the
# module with a /1 arity, otherwise fallback to grabbing from the
# entity passed in.
unquote(has_function?)
|> case do
true -> apply(__MODULE__, unquote(attr), [m, c])
false -> Map.get(m, unquote(attr))
end
end
def unquote(attr)(m, _), do: Map.get(m, unquote(attr))
defoverridable [{attr, 2}]
end
end
Expand Down

0 comments on commit 1ac0c6c

Please sign in to comment.