]> git.openstreetmap.org Git - rails.git/commitdiff
Use default og:image if Addressable::URI fails
authorAnton Khorev <tony29@yandex.ru>
Sat, 15 Jun 2024 12:57:10 +0000 (15:57 +0300)
committerAnton Khorev <tony29@yandex.ru>
Sat, 15 Jun 2024 12:57:10 +0000 (15:57 +0300)
app/helpers/open_graph_helper.rb
test/controllers/diary_entries_controller_test.rb

index b7654ee89a388821797d70b81d1edfbcf1ba215a..a41831ca69d98bc6e287c495ec94653817245b2b 100644 (file)
@@ -6,7 +6,7 @@ module OpenGraphHelper
       "og:site_name" => t("layouts.project_name.title"),
       "og:title" => title || t("layouts.project_name.title"),
       "og:type" => "website",
-      "og:image" => og_image ? Addressable::URI.join(root_url, og_image).normalize : image_url("osm_logo_256.png"),
+      "og:image" => og_image_url(og_image),
       "og:url" => url_for(:only_path => false),
       "og:description" => t("layouts.intro_text")
     }
@@ -15,4 +15,15 @@ module OpenGraphHelper
       tag.meta(:property => property, :content => content)
     end, "\n")
   end
+
+  private
+
+  def og_image_url(og_image)
+    begin
+      return Addressable::URI.join(root_url, og_image).normalize if og_image
+    rescue Addressable::URI::InvalidURIError
+      # return default image
+    end
+    image_url("osm_logo_256.png")
+  end
 end
index f3ca40f418d4a952fe8b0057b8d97f76987a44e1..c8548d67b408a3c3e463a70c994354694fde3096 100644 (file)
@@ -744,6 +744,17 @@ class DiaryEntriesControllerTest < ActionDispatch::IntegrationTest
     end
   end
 
+  def test_show_og_image_with_no_image
+    user = create(:user)
+    diary_entry = create(:diary_entry, :user => user, :body => "nothing")
+
+    get diary_entry_path(user, diary_entry)
+    assert_response :success
+    assert_dom "head meta[property='og:image']" do
+      assert_dom "> @content", ActionController::Base.helpers.image_url("osm_logo_256.png", :host => root_url)
+    end
+  end
+
   def test_show_og_image
     user = create(:user)
     diary_entry = create(:diary_entry, :user => user, :body => "![some picture](https://example.com/picture.jpg)")
@@ -788,6 +799,17 @@ class DiaryEntriesControllerTest < ActionDispatch::IntegrationTest
     end
   end
 
+  def test_show_og_image_with_invalid_uri
+    user = create(:user)
+    diary_entry = create(:diary_entry, :user => user, :body => "![](:)")
+
+    get diary_entry_path(user, diary_entry)
+    assert_response :success
+    assert_dom "head meta[property='og:image']" do
+      assert_dom "> @content", ActionController::Base.helpers.image_url("osm_logo_256.png", :host => root_url)
+    end
+  end
+
   def test_hide
     user = create(:user)
     diary_entry = create(:diary_entry, :user => user)