How to add a Pin It button to your Rails app with a dynamic URL and description

Every week, I see several people discover Coverlist via Pinterest, and it’s always from the same pin – the one of book Eleanor and Park

I want to encourage people to Pin beautiful books from Coverlist, but because the book descriptions (micro-reviews, if you will) are both short and unique, I wanted those to be represented on Pinterest as well. 

But the Pin It button was just pulling the image file name, which I could not control, because I am pulling images from Open Library’s API.

I found out that 1. Pinterest uses alt text for automatic descriptions, and 2. I had implemented alt text wrong on my book images. 

First you need to add the following code to your application.html.erb page: 

<!– Please call pinit.js only once per page –>
<script type=“text/javascript” async data-pin-hover=“true” src=“//assets.pinterest.com/js/pinit.js”></script>

Then, all your images on your site will show a Pin It button on hover. It won’t really work on mobile, but that’s OK for now. 

Then, make sure your alt text is filled in with dynamic information about whatever is on your Rails app. Mine was: 

<%= link_to image_tag(@book.cover_url), “http://openlibrary.org”, alt: @book.title + “ – ” + @book.description %>

But the Pin It button and the Pinterest bookmarklet were not finding the alt text and instead using the file name for a description. 

Then I discovered that when you have a linked image and the image info is inside parentheses, you need to include the alt inside those same parentheses. 

<%= link_to image_tag(@book.cover_url, :alt => @book.title + “ – ” + @book.description), “http://openlibrary.org” %>

Now, Coverlist images can be pinned with good descriptions – of course, anyone can change it, but at least they have something to start with.