Technical
Widgets And Rails

So I had to do a widget that will be shown’s on user of our website through js. I came across many articles that were dealing with it like Xss Widgets and
some posts that were very vague. Gladly, my friend from http://webalgorithm.com explained to me this whole ordeal in a very simple steps.

So this is what we want to do.

  1. We want to give a user js link that he/she would embed to their website in a following form.
    
    <script type="text/javascript" src="http://localhost:9090/monozub/widget.js"></script>
    
  2. To have an action on our part that would right back content using javascript
    
    document.write('<b>some html</b>');
    
  3. We needed to have a link that would have .js extension and would specify format as js

So this is how it can be done.

  1. Create a route to the widget with js format ( http://local/monozub/widget.js )
    
      map.with_options :controller => 'widget' do |m|
        m.facebook    ':username/widget', :action                      => 'show'
        m.widget_js   ':username/widget.js', :action                   => 'show',:format => "js"   
      end
    
  2. Based on the formats (available since Rails 2.0) specify what to do on js. In the further case it will by default pick up show.js.erb
    
    class WidgetController < ApplicationController
    
      def show
       #whatever logick you have goes here.
       respond_to do |format|
         format.html     
         format.js 
       end
      end
    
    end
    
  3. Finally your show.js.erb
    
    <% 3.times do |i| %>
    document.write('<b>Test <%= i %></b><br />');
    <% end %>
    

Thats it folks, no need for JASON, XSS or any other high level technologies.

NOTE: be aware IE will give you a warning, but WHO USES THAT c…p Anyway :)