From 37edcb113a5dcbdc79e6e90b53f6f643c568c437 Mon Sep 17 00:00:00 2001 From: Anton Khorev Date: Fri, 2 Aug 2024 20:19:10 +0300 Subject: [PATCH] Skip images with missing src --- lib/rich_text.rb | 7 +++++-- test/lib/rich_text_test.rb | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/lib/rich_text.rb b/lib/rich_text.rb index de35aae9c..edfa535f4 100644 --- a/lib/rich_text.rb +++ b/lib/rich_text.rb @@ -104,14 +104,17 @@ module RichText end def first_image_element(element) - return element if element.type == :img || - (element.type == :html_element && element.value == "img") + return element if image?(element) && element.attr["src"].present? element.children.find do |child| nested_image = first_image_element(child) break nested_image if nested_image end end + + def image?(element) + element.type == :img || (element.type == :html_element && element.value == "img") + end end class Text < Base diff --git a/test/lib/rich_text_test.rb b/test/lib/rich_text_test.rb index 8c1205317..e601c36fc 100644 --- a/test/lib/rich_text_test.rb +++ b/test/lib/rich_text_test.rb @@ -275,11 +275,41 @@ class RichTextTest < ActiveSupport::TestCase assert_equal "https://example.com/image1.jpg", r.image end + def test_markdown_image_with_empty_src + r = RichText.new("markdown", "![invalid]()") + assert_nil r.image + end + + def test_markdown_skip_image_with_empty_src + r = RichText.new("markdown", "![invalid]() ![valid](https://example.com/valid.gif)") + assert_equal "https://example.com/valid.gif", r.image + end + def test_markdown_html_image r = RichText.new("markdown", "") assert_equal "https://example.com/img_element.png", r.image end + def test_markdown_html_image_with_empty_src + r = RichText.new("markdown", "") + assert_nil r.image + end + + def test_markdown_skip_html_image_with_empty_src + r = RichText.new("markdown", " ") + assert_equal "https://example.com/next_img_element.png", r.image + end + + def test_markdown_html_image_without_src + r = RichText.new("markdown", "") + assert_nil r.image + end + + def test_markdown_skip_html_image_without_src + r = RichText.new("markdown", " ") + assert_equal "https://example.com/next_img_element.png", r.image + end + private def assert_html(richtext, &block) -- 2.39.5