如何使用 RuboCop 强制使用三元括号?

How can I enforce ternary parentheses with RuboCop?

我有一个编码标准,建议无论表达式如何,三元组的初始参数都应始终在括号内。

例如foo = (thing.baz?) ? [] : thing.bar

以下行为应视为违规:

例如foo = thing.baz? ? [] : thing.bar

是否可以使用 Rubocop 的内置 Cops 实现此目的,或者这是否需要自定义 Cop。如果是这样,我将如何实施?

我看到了你的问题,所以我继续为你实施警察。名称是Style/TernaryParentheses,你想要的EnforcedStyle选项是require_parentheses(不是默认的。)

# .rubocop.yml
Style/TernaryParentheses:
  Enabled: true
  EnforcedStyle: require_parentheses

您可以立即开始使用它,只需将其放入您的 Gemfile:

gem 'rubocop', git: 'git://github.com/bbatsov/rubocop.git'

或者您可以等待 0.42.0 发布。