ruby everywhere

Jared Carroll

Been doing some JavaScript apps recently in Rails and decided to push RJS as far as I could.

Along the way I found some things that are pretty nice to have on the client side to avoid having to code all your JavaScript in strings.

Using update_page

<%= link_to_function 'Yes' do |page|
      page[:one].hide
      page[:two].show
    end %>

Putting that in your views Generates the following JavaScript

<a href="#" onclick="$('one').hide();$('two').show();; return false;">Yes</a>

That page object that’s yield‘d to by #link_to_function is a JavaScriptGenerator object. The same kind you get when you do stuff like this on the serverside

def search
  respond_to do |wants|
    @users = User.search params[:q]
    wants.js
  end
end

In search.rjs:

page.update_html :results, render(:partial => 'user', :collection => @users)

There’s also #update_page_tag. This method also yield’s a JavaScriptGenerator object to the given block and then wraps the generated JavaScript in some 'script’ tags.

<%= update_page_tag do |page|
   page[:one].show
   page[:two].hide
  end %>

Generates the following JavaScript

<script type="text/javascript">
  $('one').show();
  $('two').hide();
</script>

One thing it doesn’t yet support but would be great if it did in Rails 2.0 is registering event handlers.

<%= update_page_tag do |page|
  page[:one].on_click do
    page[:two].show
  end
end %>

It would be really nice if that generated

<script type="text/javascript">
  Event.observe('one', 'click', function () {
                                  $('two').show();
                                });
</script>

Most of my existing client side JavaScript consists of registering event handlers, so I still have some JavaScript code in my views consisting of Ruby strings. With something like this, we could be close to eliminating JavaScript entirely; the same way Rails’ migrations have done with SQL.

About thoughtbot

We've been helping engineering teams deliver exceptional products for over 20 years. Our designers, developers, and product managers work closely with teams to solve your toughest software challenges through collaborative design and development. Learn more about us.