I find myself writing ugly code like the following a LOT:
<td><%=emp.title%></td>
<td><%=emp.department.name if !emp.department.nil? %></td>
<td><%=emp.site.name if !emp.site.nil?%></td>
<td><%=if (!emp.site.nil? and (!emp.site.phone.nil? or !
emp.site.phone.empty?))
emp.site.phone
else
" "
end%>
</td>
Notice all those nil? checks? Is there no easier or cleaner way of
doing this?
Hmm, perhaps one of those "message-eating nils" [1] might have a place here:
class Object
def blanker
Blanker.new(self)
end
end
class Blanker
instance_methods.each{|name| undef_method(name) unless name =~ /\A__/}
def initialize(receiver)
@receiver = receiver
end
def to_s
@receiver.to_s
end
def method_missing(*args)
unless @receiver.nil?
@receiver = @receiver.send(*args)
end
self
end
end
Now, <%= emp.blanker.department.name %> should do what you want.
A few other points:
<td><%=if (!emp.site.nil? and (!emp.site.phone.nil? or !
emp.site.phone.empty?))
emp.site.phone
else
" "
end%>
</td>
activesupport lets you replace (foo.nil? || foo.empty?) with
foo.blank? (I'm assuming you typo'd the logic a bit there...)
That gets us to:
<td><%=if !emp.site.nil? && !emp.site.phone.blank?
emp.site.phone
else
" "
end%>
</td>
As for the ' ' thing, you might like to define an #or_nbsp method:
class Object
def or_nbsp
str = to_s
str =~ /\S/ ? str : ' '
end
end
Which gets us to:
<td><%=(emp.site && emp.site.phone).or_nbsp %></td>
Or, combining with the #blanker thing above:
<td><%=emp.blanker.site.phone.or_nbsp %></td>
Thanks,
Jake
Welcome!
George.
[1] http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/17785