Beautify your views using “return”

2008 June 6
by admin

A nice way to keep your views clean and not to spoil them with condition clauses, is to use the ‘return’ statement like you would do in a method:

Take this very simple exmaple:

ugly:

unless @place
  <%= @place.name %>
end

nice:

return if @place.nil?
<%= @place.name %>

UPDATE:
There’s one pitfall, I forgot to mention: Every outout BEFORE the return statement will be discarded, so this part:

<%= "Always display this sentence" %>
return if @place.nil?
<%= @place.name %>

Will result in an empty output as well. This is quite a pitty and I’m not sure if it’s a bug or feature. A may raise it soon..

No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS