Fix non associated tinyMCE images (#1762)

* Fix non assosiated tinyMCE images
This commit is contained in:
aignatov-bio 2019-05-14 15:01:57 +02:00 committed by GitHub
parent 70c4094323
commit 1555daa0c6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 6 deletions

View file

@ -15,7 +15,7 @@ module TinyMceImages
description = self[field]
# Check tinymce for old format
description = TinyMceAsset.update_old_tinymce(description)
description = TinyMceAsset.update_old_tinymce(description, self)
tiny_mce_assets.each do |tm_asset|
tmp_f = Tempfile.open(tm_asset.image_file_name, Rails.root.join('tmp'))
@ -40,7 +40,7 @@ module TinyMceImages
end
def tinymce_render(field)
TinyMceAsset.generate_url(self[field])
TinyMceAsset.generate_url(self[field], self)
end
# Takes array of old/new TinyMCE asset ID pairs
@ -50,7 +50,7 @@ module TinyMceImages
description = read_attribute(object_field)
# Check tinymce for old format
description = TinyMceAsset.update_old_tinymce(description)
description = TinyMceAsset.update_old_tinymce(description, self)
parsed_description = Nokogiri::HTML(description)
images.each do |image|

View file

@ -48,9 +48,9 @@ class TinyMceAsset < ApplicationRecord
Rails.logger.error e.message
end
def self.generate_url(description)
def self.generate_url(description, obj = nil)
# Check tinymce for old format
description = update_old_tinymce(description)
description = update_old_tinymce(description, obj)
description = Nokogiri::HTML(description)
tm_assets = description.css('img')
@ -105,12 +105,17 @@ class TinyMceAsset < ApplicationRecord
asset.destroy if asset && !asset.saved
end
def self.update_old_tinymce(description)
def self.update_old_tinymce(description, obj = nil)
return description unless description
description.scan(/\[~tiny_mce_id:(\w+)\]/).flatten.each do |token|
old_format = /\[~tiny_mce_id:#{token}\]/
new_format = "<img src=\"\" class=\"img-responsive\" data-mce-token=\"#{Base62.encode(token.to_i)}\"/>"
asset = find_by_id(token)
# If object (step or result text) don't have direct assciation to tinyMCE image, we need copy it.
asset.clone_tinymce_asset(obj) if obj && obj != asset.object
description.sub!(old_format, new_format)
end
description
@ -132,6 +137,34 @@ class TinyMceAsset < ApplicationRecord
ostream
end
def clone_tinymce_asset(obj)
team_id = obj&.protocol&.team_id
team_id ||= obj&.result&.my_module&.protocol&.team_id
return false unless team_id
tiny_img_clone = TinyMceAsset.new(
image: image,
estimated_size: estimated_size,
object: obj,
team_id: team_id
)
tiny_img_clone.save!
obj.tiny_mce_assets << tiny_img_clone
# Prepare array of image to update
cloned_img_ids = [[id, tiny_img_clone.id]]
obj_field = Extends::RICH_TEXT_FIELD_MAPPINGS[obj.class.name]
# Update description with new format
obj.update(obj_field => TinyMceAsset.update_old_tinymce(obj[obj_field]))
# reassign images
obj.reassign_tiny_mce_image_references(cloned_img_ids)
end
private
def self_destruct