From 1746d7099c9f32798863db49b0256aa2f74d7fa6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Gaya?= <sebastien.gaya@gmail.com>
Date: Fri, 17 Dec 2021 12:20:39 +0100
Subject: [PATCH] best featured image

---
 app/models/communication/website/page.rb                   | 7 +++++++
 app/models/communication/website/with_media.rb             | 7 ++++++-
 .../admin/communication/website/pages/jekyll.html.erb      | 4 ++--
 3 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/app/models/communication/website/page.rb b/app/models/communication/website/page.rb
index f9b54aa15..cdb51a35b 100644
--- a/app/models/communication/website/page.rb
+++ b/app/models/communication/website/page.rb
@@ -86,6 +86,13 @@ class Communication::Website::Page < ApplicationRecord
     "#{ title }"
   end
 
+  def best_featured_image(fallback: true)
+    return featured_image if featured_image.attached?
+    best_image = parent&.best_featured_image(fallback: false)
+    best_image ||= featured_image if fallback
+    best_image
+  end
+
   protected
 
   def slug_unavailable?(slug)
diff --git a/app/models/communication/website/with_media.rb b/app/models/communication/website/with_media.rb
index c4aad2b35..adc5069cb 100644
--- a/app/models/communication/website/with_media.rb
+++ b/app/models/communication/website/with_media.rb
@@ -2,7 +2,12 @@ module Communication::Website::WithMedia
   extend ActiveSupport::Concern
 
   def active_storage_blobs
-    blob_ids = [featured_image&.blob_id, text.embeds.blobs.pluck(:id)].flatten.compact
+    blob_ids = [best_featured_image&.blob_id, text.embeds.blobs.pluck(:id)].flatten.compact
     university.active_storage_blobs.where(id: blob_ids)
   end
+
+  # Can be overwrite to get featured_image from associated objects (ex: parents)
+  def best_featured_image(fallback: true)
+    featured_image
+  end
 end
diff --git a/app/views/admin/communication/website/pages/jekyll.html.erb b/app/views/admin/communication/website/pages/jekyll.html.erb
index 279a44f57..619921c91 100644
--- a/app/views/admin/communication/website/pages/jekyll.html.erb
+++ b/app/views/admin/communication/website/pages/jekyll.html.erb
@@ -5,8 +5,8 @@ identifier: "<%= @page.id %>"
 parent: "<%= @page.parent_id %>"
 related_category: "<%= @page.related_category_id %>"
 position: <%= @page.position %>
-<% if @page.featured_image.attached? %>
-image: "<%= @page.featured_image.blob.id %>"
+<% if @page.best_featured_image.attached? %>
+image: "<%= @page.best_featured_image.blob.id %>"
 <% end %>
 description: >
   <%= prepare_for_github @page.description, @page.university %>
-- 
GitLab