How to build your own widget in Ruby on Rails in 10 minutes

To improve the ranking of my website in Google, I decided to provide my users with a widget they can add to their blogs or websites. I will show in this article how I did it in 30 minutes using Ruby on Rails (hopefully you will be able to do it in less than 10 minutes thanks to this article).

1. First I created the Widget controller:

def ilove
  @content = render_to_string(:partial => 'widget/ilove_widget')
  render :layout => false

2. Then I created a partial view I called _ilove_widget.rhtml:

<div class="widget-ilove">
<a href="" 
    title="Awesome freelance marketplace :)">
  <div class="line1">I <span class="heart">&hearts;</span></div>
  <div class="line2">TaskArmy</div>

3. I also wrote some css related to my widget:

.widget-ilove {
	margin-left: auto !important;
	margin-right: auto !important;
	font-size: 10px !important;
	text-align: center !important;
	width: 70px !important;
	height: 70px !important;
	border: 1px solid #ccc !important;
	padding: 0px 3px 3px 3px !important;
	-moz-border-radius: 10px !important;
	-webkit-border-radius: 10px !important;
	margin-bottom: 5px !important }
.widget-ilove .heart { color:red !important; font-size: 42px !important }
.widget-ilove a {
		font-weight: bold !important;
		color: Black !important;
		text-decoration: none !important; }
.widget-ilove:hover { background-color: #ffe !important }
.widget-ilove .line1 { font-size: 36px !important }
.widget-ilove .line2 { font-size: 12px !important }

4. Then I created a view (not a partial view, a normal view) called ilove:

(function() { document.write(<%= @content.to_json %>) })()

5. I used a css compressor to get my css into one line (I surrounded it with <style>…</style>)

6. The code people will need to add to their blogs looks like that:

<script type="text/javascript" src=""></script>

<style>.widget-ilove{ margin-left:auto; margin-right:auto; font-size:10px; text-align:center; width:70px; height:70px; border:1px solid #ccc; padding:0px 3px 3px 3px; -moz-border-radius:10px; -webkit-border-radius:10px; margin-bottom:5px}.widget-ilove .heart{ color:red; font-size:42px}.widget-ilove a{ font-weight:bold; color:Black; text-decoration:none;}.widget-ilove:hover{ background-color:#ffe}.widget-ilove .line1{ font-size:36px}.widget-ilove .line2{ font-size:12px}</style>

I then decided to add the widget to my website with a call to action to encourage my users to add the widget.

7. I html encoded the code in step 6 (referred to as HTML_ENCODED_STEP_6 in step 7)

8. Finally, I added this code to my website:

  <div style="text-align:center;">
    <a href="#" onclick="$('#widget-code').show();$('#widget-code input').focus();return false;">
      Add this badge to your blog &dArr;
  <div id="widget-code">
    Just copy and paste this code:
    <input style="width:98%" type="text" value="HTML_ENCODED_STEP_6" />

Tada! I hope you found this article useful!