Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
jsteiner committed Jan 6, 2017
1 parent 0418187 commit d2d901e
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions lib/ex_machina/ecto.ex
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ defmodule ExMachina.Ecto do
defp recursively_strip(record = %{__meta__: %{__struct__: Ecto.Schema.Metadata}}) do
record
|> strip_has_assocs
|> handle_belongs_to_assocs
|> set_persisted_belongs_to_ids
|> drop_belongs_to_assocs
|> drop_ecto_fields
|> drop_fields_with_nil_values
end
Expand Down Expand Up @@ -187,7 +188,7 @@ defmodule ExMachina.Ecto do
end
end

defp handle_belongs_to_assocs(record = %{__struct__: struct, __meta__: %{__struct__: Ecto.Schema.Metadata}}) do
defp set_persisted_belongs_to_ids(record = %{__struct__: struct, __meta__: %{__struct__: Ecto.Schema.Metadata}}) do
Enum.reduce(struct.__schema__(:associations), record, fn(association_name, record) ->
association = struct.__schema__(:association, association_name)

Expand All @@ -197,17 +198,28 @@ defmodule ExMachina.Ecto do
belongs_to = %{__meta__: %{__struct__: Ecto.Schema.Metadata, state: :loaded}} ->
record
|> set_belongs_to_primary_key(belongs_to, association)
|> Map.delete(association.field)

_ ->
Map.delete(record, association.field)
record
end
_ ->
record
end
end)
end

defp drop_belongs_to_assocs(record = %{__struct__: struct, __meta__: %{__struct__: Ecto.Schema.Metadata}}) do
Enum.reduce(struct.__schema__(:associations), record, fn(association_name, record) ->
case struct.__schema__(:association, association_name) do
%{__struct__: Ecto.Association.BelongsTo} ->
Map.delete(record, association_name)

_ ->
record
end
end)
end

defp set_belongs_to_primary_key(record, belongs_to, association) do
primary_key = Map.get(belongs_to, association.related_key)

Expand Down

0 comments on commit d2d901e

Please sign in to comment.