Add image title for comment (#19586)

* Add image title for comment

* Break out boolean logic
This commit is contained in:
Ben Halpern 2023-06-08 17:11:20 -04:00 committed by GitHub
parent a345aabc2b
commit e573ba32d1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 19 additions and 0 deletions

View file

@ -104,6 +104,10 @@ class Comment < ApplicationRecord
I18n.t("models.comment.hidden")
end
def self.title_image_only
I18n.t("models.comment.image_only")
end
def self.build_comment(params, &blk)
includes(user: :profile).new(params, &blk)
end
@ -160,6 +164,8 @@ class Comment < ApplicationRecord
return self.class.title_hidden if hidden_by_commentable_user
text = ActionController::Base.helpers.strip_tags(processed_html).strip
return self.class.title_image_only if only_contains_image?(text)
truncated_text = ActionController::Base.helpers.truncate(text, length: length).gsub("&#39;", "'").gsub("&amp;", "&")
Nokogiri::HTML.fragment(truncated_text).text # unescapes all HTML entities
end
@ -389,4 +395,9 @@ class Comment < ApplicationRecord
def parent_exists?
parent_id && Comment.exists?(id: parent_id)
end
def only_contains_image?(stripped_text)
# If stripped text is blank and processed html has <img> tags, then it's an image-only comment
stripped_text.blank? && processed_html.include?("<img")
end
end

View file

@ -47,6 +47,7 @@ en:
deleted: '[deleted]'
has_been_deleted: '%{type} has been deleted.'
hidden: '[hidden by post author]'
image_only: '[image]'
is_not_valid: is not valid.
locked: the discussion is locked on this Post
published_article: is not a published article

View file

@ -46,6 +46,7 @@ fr:
deleted: '[supprimé]'
has_been_deleted: '%{type} a été supprimé'
hidden: "[caché par l'auteur du message]"
image_only: '[image]'
is_not_valid: n'est pas valide.
locked: la discussion est verrouillée sur ce message
published_article: n'est pas un article publié

View file

@ -327,6 +327,12 @@ RSpec.describe Comment do
expect(comment.title).to eq("[deleted]")
end
it "is converted to image text if the comment is image" do
comment.body_markdown = "![image](https://myimage.com/image.png)"
comment.validate!
expect(comment.title).to eq("[image]")
end
it "does not contain the wrong encoding" do
comment.body_markdown = "It's the best post ever. It's so great."