lib/jsonapi_compliable/util/persistence.rb in jsonapi_compliable-0.8.0 vs lib/jsonapi_compliable/util/persistence.rb in jsonapi_compliable-0.9.0
- old
+ new
@@ -25,27 +25,31 @@
# * persist current object
# * associate temp id with current object
# * associate parent objects with current object
# * process children
# * associate children
+ # * run post-process sideload hooks
# * return current object
#
# @return the persisted model instance
def run
parents = process_belongs_to(@relationships)
update_foreign_key_for_parents(parents)
persisted = persist_object(@meta[:method], @attributes)
assign_temp_id(persisted, @meta[:temp_id])
+
associate_parents(persisted, parents)
children = process_has_many(@relationships, persisted) do |x|
update_foreign_key(persisted, x[:attributes], x)
end
- associate_children(persisted, children)
- persisted unless @meta[:method] == :destroy
+ associate_children(persisted, children) unless @meta[:method] == :destroy
+ post_process(persisted, parents)
+ post_process(persisted, children)
+ persisted
end
private
# The child's attributes should be modified to nil-out the
@@ -74,10 +78,13 @@
update_foreign_key(x[:object], @attributes, x)
end
end
def associate_parents(object, parents)
+ # No need to associate to destroyed objects
+ parents = parents.select { |x| x[:meta][:method] != :destroy }
+
parents.each do |x|
if x[:object] && object
if x[:meta][:method] == :disassociate
x[:sideload].disassociate(x[:object], object)
else
@@ -86,10 +93,13 @@
end
end
end
def associate_children(object, children)
+ # No need to associate destroyed objects
+ return if @meta[:method] == :destroy
+
children.each do |x|
if x[:object] && object
if x[:meta][:method] == :disassociate
x[:sideload].disassociate(object, x[:object])
else
@@ -125,9 +135,19 @@
[].tap do |processed|
iterate(only: [:polymorphic_belongs_to, :belongs_to]) do |x|
x[:object] = x[:sideload].resource
.persist_with_relationships(x[:meta], x[:attributes], x[:relationships])
processed << x
+ end
+ end
+ end
+
+ def post_process(caller_model, processed)
+ groups = processed.group_by { |x| x[:meta][:method] }
+ groups.each_pair do |method, group|
+ group.group_by { |g| g[:sideload] }.each_pair do |sideload, members|
+ objects = members.map { |x| x[:object] }
+ sideload.fire_hooks!(caller_model, objects, method)
end
end
end
def assign_temp_id(object, temp_id)