I have a banner in a sidebar that is displayed by a chunk of HTML, in my Ruby on Rails application in my views/home/index.html But I have another banner. I want to randomly display one of these, every time someone views the page.
<section id="audio-banner">
<a onclick="changeClass("#swap") href="#">
<img src="someImage.gif" >
</a>
</section>
and
<section id="audio-banner">
<a onclick="changeClass("#swap2") href="#">
<img src="someOtherImage.gif" >
</a>
</section>
I am new to Ruby and Rails. I’m not sure where to put the predefined HTML (model, controller, helper, etc.) or how to write the function that will display one of these two randomly.
I started out by editing helpers/home_helper.rb and inserted the following code
module StoreHelper
def randomAudio
audio1 = '<section id="audio-banner">'
audio1 << '<a onclick="changeClass("#swap"); return false;" href="#">'
audio1 << '<img src="some.gif">'
audio1 << '</a>'
audio1 << '</section>'
audio1
audio2 = '<section id="audio-banner">'
audio2 << '<a onclick="changeClass("#swap2"); return false;" href="#">'
audio2 << '<img src="someOther.gif" alt="Estate">'
audio2 << '</a>'
audio2 << '</section>'
audio2
end
end
But that’s as far as I got, because I know it isn’t correct. Any help would be great. Thanks.
Here’s an improved version of your code (should work). Note that in real app, you should move these HTML parts to partials. But here, for the sake of simplicity, let’s leave them inline.
It uses heredocs to define HTML snippets without extra noise. Also read about Array#sample.