Using Each with Index to Display Ruby on Rails Adsense Display Ads

Last Updated: February 06, 2018

While working on DoggieDashboard the other day, I realized that I wasn't quite sure how I would add Google Adsense banners dynamically. In the pet index view of DoggieDashboard, user pets are paginated at 50 pets per page (to keep page load times down). Well, instead of hard coding a square AdSense advertisement into the view multiple times, I wanted to figure out a way to get ads mixed into the scrolling view.

My good friends each_with_index and modulo came to the rescue. By injecting the index into the iteration, you can set the frequency of the advertisement. In the example below, I have the advertisement showing in every 7th "pet card" slot.

You might be wondering why I have index = index += 1 at the start of the loop. Since arrays and relations are zero-indexed objects you're going to run into a problem with your first index, 0. 0 % 7 = 0 Because modulo of zero equals zero, the advertisement gets inserted into the very first "pet card" slot. From a UX viewpoint, this is kind of annoying. You're expecting advertisements, but you're not expecting it to be the first thing you see. So, if you increase the index by 1, you get your first true return value for index % 7 == 0 at the 7th slot.

- @pets.each_with_index do |pet, index|
- index = index += 1
- if index % 7 == 0
#adwords javascript goes here

With the above code example, I'm able to easily insert square Google Adsense advertisements into DoggieDashboard's main pet index view. If I want to adjust my frequency, and I'm sure I will in the future, I'll probably just set up an environmental variable along the lines of if index % ENV['Ad_Frequency'] == 0 and then I'll be able to tweak my ad frequency without having to redeploy.