---
title: ruby everywhere
teaser: Tradeoffs on ruby vs javascript in Rails views.
tags: web,rails
author: Jared Carroll
published_on: 2007-10-17
---

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`

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

Putting that in your views Generates the following JavaScript

```html
<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`:

```ruby
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.

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

Generates the following JavaScript

```html
<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.

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

It would be really nice if that generated

```html
<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 <abbr title="Structured
Query Language">SQL</abbr>.
