]> git.openstreetmap.org Git - rails.git/commitdiff
Skip images with missing src
authorAnton Khorev <tony29@yandex.ru>
Fri, 2 Aug 2024 17:19:10 +0000 (20:19 +0300)
committerAnton Khorev <tony29@yandex.ru>
Fri, 2 Aug 2024 17:19:10 +0000 (20:19 +0300)
lib/rich_text.rb
test/lib/rich_text_test.rb

index de35aae9c195091ea1e0d64b0a5a95b5df8fb628..edfa535f434c07d23fb88412ad9dd673c38645d5 100644 (file)
@@ -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
index 8c12053179d2389b7575506905c49d453ef89075..e601c36fc5d3b1c27a1443985e9110840fded551 100644 (file)
@@ -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", "<img src='https://example.com/img_element.png'>")
     assert_equal "https://example.com/img_element.png", r.image
   end
 
+  def test_markdown_html_image_with_empty_src
+    r = RichText.new("markdown", "<img src=''>")
+    assert_nil r.image
+  end
+
+  def test_markdown_skip_html_image_with_empty_src
+    r = RichText.new("markdown", "<img src=''> <img src='https://example.com/next_img_element.png'>")
+    assert_equal "https://example.com/next_img_element.png", r.image
+  end
+
+  def test_markdown_html_image_without_src
+    r = RichText.new("markdown", "<img>")
+    assert_nil r.image
+  end
+
+  def test_markdown_skip_html_image_without_src
+    r = RichText.new("markdown", "<img> <img src='https://example.com/next_img_element.png'>")
+    assert_equal "https://example.com/next_img_element.png", r.image
+  end
+
   private
 
   def assert_html(richtext, &block)