Tuesday, April 25, 2006

Use params, not @params

Posted by marcel

I still frequently see people in the #rubyonrails channel using @params in their code. For a while now @params has been deprecated in favor of simply params. For those who just skim these blog posts:

Use params, not @params

Why? When you use the params method, it allows for the implementation details of the parameter hash to be changed without breaking existing code. If the implementation of params changed you wouldn’t have to change your code at all because the single point of access for the parameters would just remain the params method. So, the details of what is happening behind the scenes don’t matter. If, though, you use the @params instance variable directly, you’ve broken encapsulation and consequently the ability for the implementation to be easily modified. Methods can be refactored, but instance variables can’t. Today the params method just wraps the @params instance variable, so still using @params works, but that’s not guaranteed to always remain the case.

Same goes for request, response, session, headers, template, cookies and flash.

Basically, a good rule of thumb here is don’t use an instance variable in your controller or view unless you created that instance variable.

Even the old @content_for_layout in the layout is deprecated in favor of just using yield in its place. Also content_for('some_fragment') is now accessed with yield :some_fragment rather than @content_for_some_fragment.