From bcc798d6a78535ef69700349c9eefc1554ea365d Mon Sep 17 00:00:00 2001
From: Matt Jankowski <matt@jankowski.online>
Date: Wed, 4 Dec 2024 04:05:58 -0500
Subject: [PATCH] Fix empty authors preview card serialization (#33151)

---
 app/models/preview_card.rb                    |  9 +++-
 .../rest/preview_card_serializer_spec.rb      | 41 +++++++++++++++++++
 2 files changed, 49 insertions(+), 1 deletion(-)
 create mode 100644 spec/serializers/rest/preview_card_serializer_spec.rb

diff --git a/app/models/preview_card.rb b/app/models/preview_card.rb
index 7579178f8..f6f37c8c8 100644
--- a/app/models/preview_card.rb
+++ b/app/models/preview_card.rb
@@ -134,7 +134,7 @@ class PreviewCard < ApplicationRecord
   end
 
   def authors
-    @authors ||= [PreviewCard::Author.new(self)]
+    @authors ||= Array(serialized_authors)
   end
 
   class Author < ActiveModelSerializers::Model
@@ -169,6 +169,13 @@ class PreviewCard < ApplicationRecord
 
   private
 
+  def serialized_authors
+    if author_name? || author_url?
+      PreviewCard::Author
+        .new(self)
+    end
+  end
+
   def extract_dimensions
     file = image.queued_for_write[:original]
 
diff --git a/spec/serializers/rest/preview_card_serializer_spec.rb b/spec/serializers/rest/preview_card_serializer_spec.rb
new file mode 100644
index 000000000..6dbc33786
--- /dev/null
+++ b/spec/serializers/rest/preview_card_serializer_spec.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+RSpec.describe REST::PreviewCardSerializer do
+  subject do
+    serialized_record_json(
+      preview_card,
+      described_class
+    )
+  end
+
+  context 'when preview card does not have author data' do
+    let(:preview_card) { Fabricate.build :preview_card }
+
+    it 'includes empty authors array' do
+      expect(subject.deep_symbolize_keys)
+        .to include(
+          authors: be_an(Array).and(be_empty)
+        )
+    end
+  end
+
+  context 'when preview card has author data' do
+    let(:preview_card) { Fabricate.build :preview_card, author_name: 'Name', author_url: 'https://host.example/123' }
+
+    it 'includes populated authors array' do
+      expect(subject.deep_symbolize_keys)
+        .to include(
+          authors: be_an(Array).and(
+            contain_exactly(
+              include(
+                name: 'Name',
+                url: 'https://host.example/123'
+              )
+            )
+          )
+        )
+    end
+  end
+end