views:

627

answers:

4

Ruby on Rails has a lot of ways to generate JavaScript. Particularly when it comes to Ajax. Unfortunately, there are a few problems that I often see with the JavaScript that it generates.

  • Rails typically uses inline event handling.

    <a onclick="somejavascript(); return false;" />

    This is generally frowned upon, as it's mixing behavior in with the XHTML.

  • The generated JavaScript also relies heavily on Prototype. Personally, I prefer jQuery.

  • In my experience, the attitude with a lot of Rails developers has been to write as much of the code in Ruby as possible. The final step being to generate some very procedural and repetitive JavaScript. Often, this code ends up being very inflexible and difficult to debug.

So, my question is: how much JavaScript do you write manually for your projects and how much of it is generated server side with Rails/Ruby? Or is there a happy medium where you get the benefits of both? With a subquestion: if you write a lot of the JavaScript manually, what techniques do you use to fit it into the MVC model?

A: 

Let Rails do as much as possible. Then when you have problems, start rewriting it with hand coded versions.

madlep
A: 

none, use jquery if need be. Ajax and ie js bugs are hard to trackdown

MatthewFord
+3  A: 

I used to work in Symfony (a Rails clone) and at first, we used a lot of Javascript helpers. Client requirements led us (me!) to have to write a lot of code the helpers just couldn't generate. I eventually came to the conclusion that I prefer not to use helpers at all.

Progressive enhancement is the way to go, in my opinion. Generate standards-friendly HTML that works without JavaScript enabled, then pile on the fancy functionality on document ready.

By the way, I've also switched from Prototype to jQuery and have no desire to switch back! In my opinion, jQuery is better suited to progressive enhancement.

Andrew Hedges
I had the same issues with CakePHP helpers. Ended up hand coding in jQuery much faster and easier.
Geoff
+4  A: 

If you prefer jQuery you can use the jQuery on Rails Project. A drop in to replace Prototype with jQuery.

Some of what Rails does with Javascript generation is good and some is bad. In the bad instances, write it yourself and keep it unobtrusive. At any given time you're uncomfortable with the Javascript Rails generates, you can go ahead and write it yourself.

And be sure to check out this great intro to unobtrusive Javascript that was done with Rails in mind.

mwilliams