Tidbits of Ruby, Rails, and all things related

Pinterest extension for Spree

TL; DR

spree_pinterest is a Spree extension for adding a Pinterest Pin it
button to your Spree store. Install it by adding it to your Gemfile.

The last project I worked on, the client needed shopping cart
capabilities added to thier site. I chose to use the open-source
Spree shopping cart Rails engine.

Spree is a great piece of software that doesn’t try to cover every edge
case in the e-commerce world. It provides what 98% of most sites
need to run an online store. The last project I worked on
fell within the other 2% though, and I had to heavily customize it for that
particular project. I’ll save those customizations for another
post.

What I want to talk about today is a new Spree extension I wrote
recently, called spree_pinterest.
It’s a simple extension that adds a Pinterest
button to the Spree product index and show views.

Spree makes it really easy to create an extension. I won’t go into the
details of that here, but you can read all about that in the
Creating Extensions
section of the Spree Guides.

Creating a Pin it button

Pinterest provides the instructions
for adding a Pin it button on their website. It basically consists of two parts:

Inserting some Javascript in your page

Adding a link, which the Javascript converts to the button

The Javascript

Step 2 above is slightly misleading. The Javascript actually converts the
link to an IFRAME which contains the newly-rendered link styled as a button.
Not sure of the reason for the IFRAME. I honestly didn’t dive in to how
the Pinterest pin_it.js script actually works.

First, I added the Javascript to the spree_pinterest.js Javascript file created
when I ran the spree extension command:

This is the Javascript provided in the advanced option on the Pinterest website. I
may end up converting this to Coffescript, but I was in a hurry at the
time :)

The views

Next, we need to add the link to our views that will get converted to
the Pin it buttons. For this extension I decided to add two buttons.
One for each image on the products index view just to the left of the price,
and one directly under each image on the products show view.

There are two mandatory, and one optional pieces of information you need
to supply in the href of the link:

url (mandatory) - This is the product page URL

media (mandatory) - This is the URL to the image which is being
pinned. In the event you’ve specified an asset_host for your app,
or you are using S3 with paperclip, the URL will be used as is. If
not, the url method from paperclip will only be a path, so the
helper will prepend the protocol and host.

description (optional) - This is the description that will be used in
the pin

You can see the values being used for each of the variables in lines 6-8
above.

Now we need to add the links to the views. For this I used a
Deface override.
I created one override file that contains two Deface overrides, one for
each view: