Adding Social Bookmarks in Rails

Thinking of adding some social bookmarklets to your Rails project? Well, you should! It's a great way to drive traffic to your site and get that extra exposure. Now, while refactoring some of my code from 'Graphics World' I figured I should share this snippet since it's fairly tedious to setup. Here it is, in all its glory:

    <%  current_uri = u(request.protocol << request.host_with_port << request.request_uri)
        title = u(@title)

        bookmarklets = {
            :delicious => ['del.icio.us', 'delicious.gif' ,'http://del.icio.us/post?url=&amp;title='],
            :digg => ['digg it', 'digg.gif', 'http://digg.com/submit?phase=2&amp;url=&amp;title='],
            :yahoo => ['yahoo', 'yahoo.gif', 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=&amp;t='],
        }
     %>

   <div>
      <% bookmarklets.each_value { |bookmarklet|
            bookmarklet[2].gsub!(/\{\{url\}\}/, current_uri)
            bookmarklet[2].gsub!(/(\{\{url_encoded_title\}\})|(\{\{title\}\})/, title) -%>

        <p><a href="<%= bookmarklet[-1] %>" title="<%= bookmarklet[0] %>:<%= title %>">
            <img src="/images/social/<%= bookmarklet[1] %>" alt="<%= bookmarklet[0] %>" /> <%= bookmarklet[0] %>
        </a></p>
      <% } %>
   </div>

You can see a quick preview of the results on the left. If you don't like the layout or need to adjust the formatting just change the xhtml at the bottom of the template. You can also add/remove bookmarklets you wish to include by simply commenting out the hash values. Each value points to an array where first field is the service name, second is the image name (just in case), and third is the URL on which we will run a regex.

Note that I'm using code above as a shared template, but you could easily turn this into a helper function. Also, I assume that you have a @title variable which corresponds to your current page title. If you use static titles, or a different scheme altogether, you'll have to modify it accordingly. And last, but not least, make sure you keep the u(...) function around the current URI and page title - it's there to URL encode both variables ('My Title' turns into 'My%20Title').

Ilya GrigorikIlya Grigorik is a web ecosystem engineer, author of High Performance Browser Networking (O'Reilly), and Principal Engineer at Shopify — follow on Twitter.