views:

49

answers:

3

I'm finding I often have to use a structure to avoid a Rails error of undefined method 'name' for nil:NilClass.

The structure looks like this:

 if country.state
   country.state.name
 end

It seems like a classic case of repeating oneself with country.state appearing twice in one simple block. Is there any way to DRY this up?

+2  A: 

Well not really. One option is to install the andand gem, but introducing a dependency for this may be a little much.

yxhuvud
+1  A: 

Other than using the slightly more concise syntax of:

country.state.name unless country.state.nil?

I don't think there's a DRY way to do this with the information given. I would argue that if you can't be sure whether country.state is nil or not, you may want to look at the code responsible for setting that value and determine whether that's a normal case or whether a validator upstream should be catching that.

brokenbeatnik
Some of the `country.state`'s are nil because there was no information for those states in the original data.
Reed G. Law
Could also be country.state.name if country.state
Yannis
Good call Yannis. Reed, yeah, nothing you can really do about that then I suppose. . . your validation can only as strict as your data allows.
brokenbeatnik
+4  A: 

Rails adds a try method to object that mimics object#send but does not raise an exception if the object returns nil.

I think the syntax is

country.try(:state).name
Steve Weet
This method works, but I have to phrase it like this: `State.try(:find_by_iso, "AF").try(:country).try(:name)`
Reed G. Law
@Steve: Shouldn't it be `country.state.try(:name)` instead?
Mladen Jablanović