Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - mixing of 'send' and 'try'

I have an object which could be nil. In the next line i am getting any one of the object's argument dynamically based on some condition. I was using object.try() with if else block. Now I want to use send() so that I can achieve some 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 searching for something like try.

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

Any help?!

like image 294
Suganya Avatar asked Mar 22 '15 12:03

Suganya


2 Answers

After trying for one hour i figured out the solution.

Hats off to Rails try method.

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

like image 123
Suganya Avatar answered Nov 05 '22 00:11

Suganya


A bit cleaner way is simply:

  mes_record.try(form.to_sym) || 'not available'
like image 42
hellion Avatar answered Nov 05 '22 00:11

hellion