qnm qnm - 2 months ago 6x
Ruby Question

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.


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

The following should be considered an infraction:

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?


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
  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.