Rails - a mix of send and try

I have an object that may be nil. In the next line, I get any of the object arguments dynamically based on some condition. I used object.try () with if else block. Now I want to use send () to get efficient code.

form_name = 'parent' ( received from argument )
mes_record = Mark.first ( this can be nil )

if x == condition_1
    mes_record.parent
elsif x == condition_2
    mes_record.brother
elsif x == condition_3
    mes_record.sister
else
    mes_record.father
end

Now I want to avoid the if else ladder and use send.

 if mes_record.present?
      mes_record.send("#{form}")
 else
      mes_record = 'not available'
 end

I am looking for something like try.

   mes_record.try("dynamically substitute the attribute name here.") || 'not available'

Any help ?!

+4
source share
1 answer

After trying for an hour, I found out a solution.

Hats on the Rails validation method.

mes_record.try (: send, "# {form}") || 'not available'

+5
source

All Articles