Skip to content

Commit

Permalink
Reduce the number of requests when reifying items.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ilya Slepov authored and jaredbeck committed May 3, 2020
1 parent 9b41e62 commit d504c6a
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions lib/paper_trail/reifier.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,23 +52,23 @@ def apply_defaults_to(options, version)
# not the actual subclass. If `type` is present but empty, the class is
# the base class.
def init_model(attrs, options, version)
if options[:dup] != true && version.item
model = version.item
if options[:unversioned_attributes] == :nil
init_unversioned_attrs(attrs, model)
end
else
klass = version_reification_class(version, attrs)
# The `dup` option always returns a new object, otherwise we should
# attempt to look for the item outside of default scope(s).
find_cond = { klass.primary_key => version.item_id }
if options[:dup] || (item_found = klass.unscoped.where(find_cond).first).nil?
model = klass.new
elsif options[:unversioned_attributes] == :nil
model = item_found
init_unversioned_attrs(attrs, model)
end
klass = version_reification_class(version, attrs)

# The `dup` option and destroyed version always returns a new object,
# otherwise we should attempt to load item or to look for the item
# outside of default scope(s).
model = if options[:dup] == true || destroy_event?(version)
klass.new
else
find_cond = { klass.primary_key => version.item_id }

version.item || klass.unscoped.where(find_cond).first || klass.new
end

if options[:unversioned_attributes] == :nil && !model.new_record?
init_unversioned_attrs(attrs, model)
end

model
end

Expand Down Expand Up @@ -125,6 +125,10 @@ def version_reification_class(version, attrs)
class_name = inher_col_value.blank? ? version.item_type : inher_col_value
class_name.constantize
end

def destroy_event?(version)
version.event == "destroy"
end
end
end
end

0 comments on commit d504c6a

Please sign in to comment.