Last active
June 24, 2016 12:48
-
-
Save Bajena/d4650d2cafe11bbca6fa0d2850f09fe9 to your computer and use it in GitHub Desktop.
Monkey patch for storing file changes in paper_trail version object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module PaperTrail | |
module Model | |
module InstanceMethods | |
private | |
def changes_for_paper_trail | |
notable_changes = changes.delete_if { |k, _v| !notably_changed.include?(k) } | |
AttributeSerializers::ObjectChangesAttribute. | |
new(self.class). | |
serialize(notable_changes) | |
if defined?(CarrierWave::Uploader::Base) | |
changes_hash_with_carrierwave(notable_changes) | |
else | |
notable_changes.to_hash | |
end | |
end | |
def changes_hash_with_carrierwave(notable_changes) | |
Hash[ | |
notable_changes.to_hash.map do |attribute, values| | |
values_formatter = ValuesFormatter.new(self, attribute, values.first, values.last) | |
values_formatter.format! | |
[ | |
attribute, | |
[ | |
values_formatter.before, | |
values_formatter.after | |
] | |
] | |
end | |
] | |
end | |
class ValuesFormatter | |
def initialize(model, attribute, before, after) | |
self.model = model | |
self.attribute = attribute | |
self.before = before | |
self.after = after | |
end | |
attr_accessor :model, :attribute, :before, :after | |
def format! | |
return if !(is_uploader?(before) || is_uploader?(after)) | |
self.before = format_before_value(before) | |
self.after = format_after_value(after) | |
end | |
private | |
def format_before_value(value) | |
if is_uploader?(value) | |
format_before_uploader_value(value) | |
else | |
format_non_uploader_value(value) | |
end | |
end | |
def format_after_value(value) | |
if is_uploader?(value) | |
format_after_uploader_value(value) | |
else | |
format_non_uploader_value(value) | |
end | |
end | |
def format_non_uploader_value(value) | |
store_path(value) | |
end | |
def format_before_uploader_value(value) | |
return unless value.file | |
store_path(value.file.original_filename) | |
end | |
def format_after_uploader_value(value) | |
return if model.public_send("remove_#{attribute}").to_bool | |
store_path(value.file.original_filename) | |
end | |
def is_uploader?(value) | |
value.is_a?(CarrierWave::Uploader::Base) | |
end | |
def store_path(filename) | |
(is_uploader?(before) ? before : after).store_path(filename) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment