Rails - 'send' 和 'try' 的混合
Rails - mixing of 'send' and 'try'
我有一个可能为零的对象。在下一行中,我将根据某些条件动态获取对象的任何一个参数。我在 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
现在我想避开 if else 阶梯并使用 send。
if mes_record.present?
mes_record.send("#{form}")
else
mes_record = 'not available'
end
我正在搜索类似 try 的内容。
mes_record.try("dynamically substitute the attribute name here.") || 'not available'
有什么帮助吗?!
尝试了一个小时后,我找到了解决方案。
向Rails 尝试方法致敬。
mes_record.try(:send, "#{form}") || 'not available'
更简洁的方法是:
mes_record.try(form.to_sym) || 'not available'
我有一个可能为零的对象。在下一行中,我将根据某些条件动态获取对象的任何一个参数。我在 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
现在我想避开 if else 阶梯并使用 send。
if mes_record.present?
mes_record.send("#{form}")
else
mes_record = 'not available'
end
我正在搜索类似 try 的内容。
mes_record.try("dynamically substitute the attribute name here.") || 'not available'
有什么帮助吗?!
尝试了一个小时后,我找到了解决方案。
向Rails 尝试方法致敬。
mes_record.try(:send, "#{form}") || 'not available'
更简洁的方法是:
mes_record.try(form.to_sym) || 'not available'