As an alternative to the syntax in badp’s answer, I’d like to propose:
@products =
if params[:category]
Category.find(params[:category]).products
else
Product.all
end
I claim this has two advantages:
- Uniform indentation: each level of logical nesting is indented by exactly two spaces (OK, maybe this is just a matter of taste)
- Horizontal compactness: A longer variable name will not push the indented code past the 80 (or whatever) column mark
It does take an extra line of code, which I would normally dislike, but in this case it seems worthwhile to trade vertical minimalism for horizontal minimalism.
Disclaimer: this is my own idiosyncratic approach and I don’t know to what extent it is used elsewhere in the Ruby community.
Edit: I should mention that matsadler’s answer is also similar to this one. I do think having some indentation is helpful. I hope that’s enough to justify making this a separate answer.