Nil and empty

First, hats off to rails and the community. I’m definitely a convert.

Question: I’m constantly outputting information like so:

<% unless item.empty? %>

Item: <%= item %>

<% end %>

But I’m finding that depending on where item is pulled from, the item
will
either be empty (ie form), or null (ie db). Short of always checking
for
nil first then empty, what’s the easiest way to just use empty and have
that
stop throwing errors if it’s called on a null object?

Thanks,

Chad

Chad A. wrote:

Try calling blank? instead of empty?

Matthew M.
blog.mattmargolis.net

On 10/17/06, Chad A. [email protected] wrote:

You can have a little rescue clause in there if you like.

Item: <%= item rescue “N/A” %>

That should stop the errors from coming. If you search around this has
been
discussed a number of times. Also checkout rails.techno-weenie.net I
think
there are also some questions there as well.

Hope that helps.

Daniel N wrote:

On 10/17/06, Chad A. [email protected] wrote:

Short of always checking for
nil first then empty, what’s the easiest way to just use empty and have that
stop throwing errors if it’s called on a null object?

You can have a little rescue clause in there if you like.

Item: <%= item rescue “N/A” %>

That should stop the errors from coming.

As well as a multitude of other possible errors that might arise from
that method call. A big naked catch-all ‘rescue’ like that scares me –
if something unexpected happens, you’ll get no notification of it, and
it will make the bug trickier to track down.

Much better to just deal with the specific situation – in this case,
check for nil and then check for empty, which blank?() does for you.

Chris

Thanks guys… Ya I searched a bit and for some reason didn’t seem to
find a definitive answer.

Blank works perfectly for now!