Thursday, May 01, 2008

Consistency on Rails

The Ruby on Rails crowd makes a big deal about consistency. They claim that Rails is easy and fast for development partially because it favors convention over configuration. I guess the thought is that you don't need to write any configuration. Plus, once you've worked on a few Rails apps, you pretty much know where everything is.

So far, I've found a lot of that to be pretty much true. Migrations, routes, controllers, views, database configuration - there's a place for all of them, and they're pretty much exactly where I would expect them. However, I've often found myself struggling when actually writing the code. I'm either going to the documentation constantly, or even peeking in the Rails source. (It turns out that some options to methods aren't documented, and the rails plugins that we are using have poorer documentation than the core).

I only have 2 small examples at hand, but I could write about many more annoyances.
  • link_to and link_to_remote both seem similar on the surface. One will generate a normal hyperlink that will navigate the browser; the other will generate an AJAX link that will interpret the resultant response as either HTML to be embedded or Javascript to be executed.

    Both allow you to specify the url using :controller and :action. However, they have very different signatures, and it trips me up everytime.
    link_to "Help", { :controller => :help, :action => :sample }
    link_to_remote "Help", :url => { :action => :help, :action => :sample }
    Did you see that? The only difference between the two is that one requires the URL-related options to be packaged in a hash named :url, while the other disallows the hash
  • When using the form helper methods such as text_field and text_field_tag, you must be careful. Here is an example:
    text_field :post, :name <input id="foo_bar" name="foo[bar]" size="30" type="text" />
    text_field_tag 'post[name]' <input id="foo[bar]" name="foo[bar]" type="text" />
    As you can see, if you change from one to the other, you might need to also update you RJS files (or remember to set an explicit ID). This would have all been avoided if text_field had simply generated id and name attributes with the same value.
Rails certainly has its good points, but the small details are sometimes infuriating.

No comments: