From 0c8b1452926278b8e025d41b60ce92ba65207f10 Mon Sep 17 00:00:00 2001 From: krillan49 <126559400+krillan49@users.noreply.github.com> Date: Mon, 20 Jan 2025 17:34:59 +0300 Subject: [PATCH] 5#random podcast by day (#21) --- app/controllers/home_controller.rb | 2 +- app/models/podcast.rb | 9 +++++++++ app/views/home/_list.html.erb | 14 ++++++++++--- spec/features/home_page_spec.rb | 32 ++++++++++++++++++++++++++++++ 4 files changed, 53 insertions(+), 4 deletions(-) diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 18c54ab..7c30ca8 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -2,7 +2,7 @@ class HomeController < ApplicationController allow_unauthenticated_access def index - @random_podcast = Podcast.offset(rand(Podcast.count)).first # TODO: use cron + @random_podcast = Podcast.random_by_day @last_podcast = Podcast.last end end diff --git a/app/models/podcast.rb b/app/models/podcast.rb index 789856d..92cd1ff 100644 --- a/app/models/podcast.rb +++ b/app/models/podcast.rb @@ -4,4 +4,13 @@ class Podcast < ApplicationRecord validates :title, presence: true validates :title, length: { minimum: 2 } + + def self.random_by_day + return unless exists? + + cached_random_podcast_id = Rails.cache.fetch("random_podcast_id", expires_in: 1.days) do + offset(rand(Podcast.count)).first.id + end + find_by(id: cached_random_podcast_id) + end end diff --git a/app/views/home/_list.html.erb b/app/views/home/_list.html.erb index 29ca0f6..02a58c5 100644 --- a/app/views/home/_list.html.erb +++ b/app/views/home/_list.html.erb @@ -1,7 +1,11 @@ <% if Podcast.any? %>