This Gist compares two different patterns to writing your controllers. My personal preference is orders_first_controller.rb
, please feel free to comment with pros and cons of both patterns.
For this example we are using locals in both examples since instance variables encourage a leaky controller and views.
Machine comparisons were performed with flog and flay
Both scored a 0 on flay.
There are a couple of reasons that I like this implementation.
The first is dealing with global state:
With ivars you are encouraging global state usage throughout the controller, views, partial views and helpers. Global state is a slippery slope and in my opinion is best avoided. With an ivar of
@order
there is no way to control the usage of that ivar in a partial or in a helper. If you start down that path it is difficult to find where these ivars are being created. There are several instances where ivars are being created inbefore_action
methods within the controller or the application controller itself. With explicit locals you can be sure that you know where they are being passed in and can easily find the declaration. You may even go as far as coming up with a convention such as@_order
where an underscore denotes that this is "private" and you should not see it anywhere outside the controller.The second point is about
render_*
methods:For simpler controllers that pass a single object to the view, you may not see the benefit of this approach immediately. However when you start passing multiple items to the view, having a way to ensure that you are passing everything that the view needs to render properly is much less error-prone. I can't remember the number of times that I have seen errors where a collection was not initialized in the
create
orupdate
action that was all of a sudden needed because thenew
oredit
needed to be re-rendered due to a validation error. This approach eliminates that error altogether.