Skip to content

Commit

Permalink
complex method simplify and add adaptor to modelconfig options
Browse files Browse the repository at this point in the history
  • Loading branch information
kindtiger95 committed Dec 14, 2024
1 parent 68c53bd commit 878978f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 17 deletions.
23 changes: 14 additions & 9 deletions lib/paper_trail/events/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -283,15 +283,8 @@ def prepare_object_changes(changes)
# @api private
# @param changes HashWithIndifferentAccess
def recordable_object_changes(changes)
if PaperTrail.config.object_changes_adapter.respond_to?(:diff)
# We'd like to avoid the `to_hash` here, because it increases memory
# usage, but that would be a breaking change because
# `object_changes_adapter` expects a plain `Hash`, not a
# `HashWithIndifferentAccess`.
changes = PaperTrail.config.object_changes_adapter.diff(changes.to_hash)
elsif @record.class.paper_trail.object_changes_adapter&.respond_to?(:diff)
changes = @record.class.paper_trail.object_changes_adapter.diff(changes.to_hash)
end
adapter = object_changes_adapter_for_record
changes = apply_diff(changes, adapter) if adapter.respond_to?(:diff)

if @record.class.paper_trail.version_class.object_changes_col_is_json?
changes
Expand All @@ -300,6 +293,18 @@ def recordable_object_changes(changes)
end
end

def object_changes_adapter_for_record
if @record.class.paper_trail.object_changes_adapter.respond_to?(:diff)
@record.class.paper_trail.object_changes_adapter
else
PaperTrail.config.object_changes_adapter
end
end

def apply_diff(changes, adapter)
adapter.diff(changes.to_hash)
end

# Returns a boolean indicating whether to store serialized version diffs
# in the `object_changes` column of the version record.
#
Expand Down
10 changes: 2 additions & 8 deletions lib/paper_trail/model_config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def version_class
end

def object_changes_adapter
@model_class.object_changes_adapter
@model_class.paper_trail_options[:object_changes_adapter]
end

private
Expand Down Expand Up @@ -256,13 +256,7 @@ def setup_options(options)
@model_class.paper_trail_options[k] = event_attribute_option(k)
end
@model_class.paper_trail_options[:meta] ||= {}
end

def setup_custom_object_changes_adapter(options)
@model_class.class_attribute :object_changes_adapter
@model_class.object_changes_adapter = options[:object_changes_adapter]

@model_class.send :attr_accessor, @model_class.object_changes_adapter
@model_class.paper_trail_options[:object_changes_adapter] = options[:object_changes_adapter]
end
end
end

0 comments on commit 878978f

Please sign in to comment.