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? %>
- ... + <% if @last_podcast.photo.attached? %> + <%= image_tag @last_podcast.photo, class: "card-img-top", alt: "last podcast" %> + <% else %> + last podcast + <% end %>
<%= link_to @last_podcast.title, @last_podcast, @@ -14,8 +18,12 @@ <%= @last_podcast.created_at %>
-
- ... +
+ <% if @random_podcast.photo.attached? %> + <%= image_tag @random_podcast.photo, class: "card-img-top", alt: "random podcast" %> + <% else %> + random podcast + <% end %>
<%= link_to @random_podcast.title, @random_podcast, diff --git a/spec/features/home_page_spec.rb b/spec/features/home_page_spec.rb index 96e6757..095eb7a 100644 --- a/spec/features/home_page_spec.rb +++ b/spec/features/home_page_spec.rb @@ -5,6 +5,38 @@ 10.times { FactoryBot.create(:podcast) } end + context "random podcast" do + # connect the cache to the tests only in this block + let(:memory_store) { ActiveSupport::Cache.lookup_store(:memory_store) } + let(:cache) { Rails.cache } + + before do + allow(Rails).to receive(:cache).and_return(memory_store) + Rails.cache.clear + end + + scenario "by default" do + visit root_path + + random_podcast_id = Rails.cache.read("random_podcast_id") + + expect(random_podcast_id).to be_present + expect(Podcast.exists?(id: random_podcast_id)).to be_truthy + expect(page).to have_selector("#random_podcast") + end + + scenario "forced" do + Rails.cache.write("random_podcast_id", 6, expires_in: 1.days) + visit root_path + + random_podcast_id = Rails.cache.read("random_podcast_id") + + expect(random_podcast_id).to eq(6) + expect(Podcast.exists?(id: 6)).to be_truthy + expect(page).to have_selector("#random_podcast") + end + end + context do before { visit root_path }