diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 910f1f431..baeb44327 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -937,26 +937,26 @@ module ApplicationHelper return if options[:inline_attachments] == false # when using an image link, try to use an attachment, if possible - attachments = options[:attachments] || [] - if obj.is_a?(Journal) - attachments += obj.journalized.attachments if obj.journalized.respond_to?(:attachments) - else - attachments += obj.attachments if obj.respond_to?(:attachments) - end - if attachments.present? - text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png|webp))"(\s+alt="([^"]*)")?/i) do |m| - filename, ext, alt, alttext = $1, $2, $3, $4 - # search for the picture in attachments - if found = Attachment.latest_attach(attachments, CGI.unescape(filename)) - image_url = download_named_attachment_url(found, found.filename, :only_path => only_path) - desc = found.description.to_s.delete('"') - if !desc.blank? && alttext.blank? - alt = " title=\"#{desc}\" alt=\"#{desc}\"" - end - "src=\"#{image_url}\"#{alt} loading=\"lazy\"" - else - m + attachments = nil + text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png|webp))"(\s+alt="([^"]*)")?/i) do |m| + # Load attachments only if not already loaded + attachments ||= + options[:attachments].to_a + + (obj.is_a?(Journal) ? obj.journalized.try(:attachments).to_a : obj.try(:attachments).to_a) + # If no attachments, skip processing + next m if attachments.empty? + + filename, ext, alt, alttext = $1, $2, $3, $4 + # search for the picture in attachments + if found = Attachment.latest_attach(attachments, CGI.unescape(filename)) + image_url = download_named_attachment_url(found, found.filename, :only_path => only_path) + desc = found.description.to_s.delete('"') + if !desc.blank? && alttext.blank? + alt = " title=\"#{desc}\" alt=\"#{desc}\"" end + "src=\"#{image_url}\"#{alt} loading=\"lazy\"" + else + m end end end