Reputation: 111
Trying to serve a random video on each time a user either comes to the website or refreshes the homepage. This will allow it to look different and refreshing each time.
Current code for the home.html
<div class="home-banner basic-banner static video-container hidden-xs hidden-sm">
<%= @random_video %><%= video_tag "test-3.mp4, test-4.mp4", autoplay: true, loop: true, muted: true, class: "video" %>
<div class="container">
<div class="title text-center">
<h1 class="border border-color-white border-thick">PARADISE<br>BELOW</h1>
</div>
</div>
</div>
Videos are coming from /app/assets/videos/
Static Controller
def home
@tour_category = TourCategory.all
@videos = ["app/assets/videos"]
@random_no = rand(2)
@random_video = @videos[@random_no]
end
The random functions works, although it only displays the title of the video on on load or refresh. example: test-3.mp4 , refresh : test-4.mp4
So now its only to get the videos to play correctly instead of showing the title.
Been looking at this for help: http://www.java2s.com/Code/Ruby/Rails/Displayrandomimage.htm
Thanks for the help.
Upvotes: 1
Views: 51
Reputation: 957
Your code is straightforward to the solution, but you have to fix 3 points:
@videos
just an array of string "app/assets/videos"
, not array of filesvideo_tag
with your random-ed video. Since you use it with "test-3.mp4, test-4.mp4"
string, that why it generated a wrong video HTML. video_tag
need video file name, not file, so again your random logic did not solve it.To achieve the result,
Your random logic should look like
videos = Dir.glob("#{Rails.root}/app/assets/videos/*.mp4")
random_video_path = videos.sample
@random_video_name = File.basename(random_video_path)
And use it in your view
<%= video_tag @random_video_name, autoplay: true, loop: true, muted: true, class: "video" %>
Rails will do the rest for you, including generating the correct video URL.
Upvotes: 1