How to dry the ruby ​​symbol structure needed for Rails

I find that I often have to use structure to avoid a Rails error undefined method 'name' for nil:NilClass.

The structure is as follows:

 if country.state
   country.state.name
 end

It seems that the classic case of repeating oneself with country.stateappears twice in one simple block. Is there a DRY way of doing this?

+3
source share
3 answers

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

I think the syntax

country.try(:state).name
+4
source
+2

In addition to using more concise syntax:

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

I do not think there is a DRY way to do this with the information provided. I would say that if you cannot be sure that country.state is nothing or not, you can look at the code responsible for setting this value and determine whether this normal register should check if it should be.

+1
source

Source: https://habr.com/ru/post/1765362/


All Articles