Skip to content

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:
[ruby]
unless @place
<%= @place.name %>
end
[/ruby]

nice:
[ruby]
return if @place.nil?
<%= @place.name %>
[/ruby]

UPDATE:
There’s one pitfall, I forgot to mention: Every outout BEFORE the return statement will be discarded, so this part:
[ruby]
<%= "Always display this sentence" %>
return if @place.nil?
<%= @place.name %>
[/ruby]

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..

Flattr this!

Comments are closed.