qnm
qnm

Reputation: 521

How can I enforce ternary parentheses with RuboCop?

I have a coding standard that suggests that the initial argument to a ternary should always be inside parenthesis, regardless of the expression.

E.g. foo = (thing.baz?) ? [] : thing.bar

The following should be considered an infraction:

E.g. foo = thing.baz? ? [] : thing.bar

Is it possible to achieve this with Rubocop's built-in Cops, or does this require a custom Cop. If so, how would I implement it?

Upvotes: 6

Views: 652

Answers (1)

Drenmi
Drenmi

Reputation: 8777

I saw your question, so I went ahead and implemented the cop for you. The name is Style/TernaryParentheses, and the EnforcedStyle option you want is require_parentheses (not the default.)

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

You can start using it right now, by putting this in your Gemfile:

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

or you can wait for the 0.42.0 release.

Upvotes: 14

Related Questions