简体   繁体   English

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

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

I have to modify my if block from one line.我必须从一行修改我的 if 块。

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

to something like this:像这样:

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

This is simple but my rubocop's screaming Use a guard clause instead of wrapping the code inside a conditional expression .这很简单,但我的 rubocop 尖叫Use a guard clause instead of wrapping the code inside a conditional expression中。 If I add Success before last end few of my specs fail with error如果我在最后end之前添加Success ,我的一些规范会因错误而失败

expected the response to have status code (422) but it was:ok (200)期望响应具有状态代码(422)但它是:好的(200)

Without Success everything pass as it should.没有Success ,一切都会如其所愿地过去。

AFAIK, Rubocop is complaining about not returning early. AFAIK,Rubocop 抱怨不早点回来。 This should solve the Rubocop problem:这应该可以解决 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

Read more about the guard clause .阅读有关保护条款的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM