Ruby/Rails 从一行扩展 if 块 - rubocop

Ruby/Rails expansion of the if block from one line - rubocop

我必须从一行修改我的 if 块。

def filename
 "#{model.external_id}-inquiry_process_summary_#{timestamp}.pdf" if original_filename
end

像这样:

def filename
  if original_filename
    result = model.inquiry_field_responses.joins(:inquiry_field).where(inquiry_fields: { name: 'company_name' })
    "#{result.first&.value}-inquiry_process_summary_#{timestamp}.pdf"
  end
end

这很简单,但我的 rubocop 在尖叫 Use a guard clause instead of wrapping the code inside a conditional expression。如果我在最后一个 end 之前添加 Success,我的一些规范会因错误

而失败

expected the response to have status code (422) but it was :ok (200)

没有 Success 一切都会按预期进行。

据我所知,Rubocop 正在抱怨没有早点回来。这应该可以解决 Rubocop 问题:

def filename
  return unless original_filename

  result = model.inquiry_field_responses.joins(:inquiry_field).where(inquiry_fields: { name: 'company_name' })
  "#{result.first&.value}-inquiry_process_summary_#{timestamp}.pdf"
end

阅读有关 guard clause 的更多信息。