Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I enforce ternary parentheses with RuboCop?

Tags:

ruby

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?

like image 234
qnm Avatar asked Jul 07 '16 04:07

qnm


1 Answers

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.

like image 186
Drenmi Avatar answered Nov 12 '22 14:11

Drenmi