I had some code that looked similar to this:
foo = SomeActiveRecordModel.where(bar: 10).first.foo rescue ''
Once I started using Rubocop it was yelling at me for the rescue syntax there. So I figured there were at least two other ways to write this code them being:
foo =
begin
foo = SomeActiveRecordModel.where(bar: 10).first.foo
rescue NoMethodError
''
end
And:
foo = SomeActiveRecordModel.where(bar: 10).first
foo.present? ? foo.foo : ''
Which of these ways would be preferred, or is there an alternative way that is preferred?
The usual rule of thumb is that exceptions should be reserved for exceptional circumstances, those that you don't expect in the normal flow of control. For one thing, they're usually slower than the alternatives.
Here's what I prefer for your scenario:
foo = SomeActiveRecordModel.find_by_bar(10).try(:foo) || ''