Rails - 混合'发送'和'尝试'

Sug*_*nya 5 attributes ruby-on-rails dynamic

我有一个可能是零的对象.在下一行中,我根据某些条件动态获取对象的任何一个参数.我正在使用带有if else块的object.try().现在我想使用send()以便我可以实现一些有效的代码.

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
Run Code Online (Sandbox Code Playgroud)

现在我想避免使用if else梯子并使用send.

 if mes_record.present?
      mes_record.send("#{form}")
 else
      mes_record = 'not available'
 end
Run Code Online (Sandbox Code Playgroud)

我正在寻找类似尝试的东西.

   mes_record.try("dynamically substitute the attribute name here.") || 'not available'
Run Code Online (Sandbox Code Playgroud)

有什么帮助?!

hel*_*ion 7

更干净的方法很简单:

  mes_record.try(form.to_sym) || 'not available'
Run Code Online (Sandbox Code Playgroud)


Sug*_*nya 6

尝试了一个小时后,我找到了解决方案.

帽子到Rails尝试方法.

mes_record.try(:send,"#{form}")|| '无法使用'

  • 这是多余的;`try` 与 `send` 做同样的事情,只是不会引发异常。在调用发送之前,您应该只使用 try 或使用安全导航 (&),尽管一般来说,OP 的方法在这里是不好的做法,并且表明代码味道。 (3认同)