Parameter Lists Rubocop

Posted by Jason Noble on 02/19/2015 in rubocop, ruby, Uncategorized |

RuboCop Logo

Rubocop is a Ruby static code analyzer. Rubocop utilizes a number of style rules, which it calls “Cops”, hence the name.

I picked a cop at random, and wanted to see what it looks for in my Ruby code. So let’s take a look at Parameter Lists

cd ~/workspace/davinci_coders_t1_2015/practice
mkdir parameter_list_rubocop
cd parameter_list_rubocop
echo '2.1.5' > .ruby-version
echo 'davinci_coders' > .ruby-gemset
cd .

Here I’m going into my practice directory and making a new one. I then setup the directory to have RVM load Ruby 2.1.5 and the davinci_coders gemset. Next I need to add the guard-rubocop gem.

# Gemfile
source 'https://rubygems.org'

gem 'guard-rubocop'

Next we need to bundle in order to install these gems. Then we’ll initialize guard.

guard init

Now we need to tell Guard to ignore the Guardfile.

# .rubocop.yml
    - 'Guardfile'

We’ll fire up Guard, and we get no offenses. Let’s add a Ruby file called program_1.rb.

#!/usr/bin/env ruby

# I'm looking at https://github.com/bbatsov/rubocop/blob/master/lib/rubocop/cop/metrics/parameter_lists.rb

def foo(param1)
  puts param1

def foo2(param1, param2)
  puts param1, param2

def foo3(param1, param2, param3)
  puts param1, param2, param3

def foo4(param1, param2, param3, param4)
  puts param1, param2, param3, param4

def foo5(param1, param2, param3, param4, param5)
  puts param1, param2, param3, param4, param5

def foo6(param1, param2, param3, param4, param5, param6)
  puts param1, param2, param3, param4, param5, param6

def foo7(param1, param2, param3, param4, param5, param6, param7)
  puts param1, param2, param3, param4, param5, param6, param7

def foo8(param1, param2, param3, param4, param5, param6, param7, param8)
  puts param1, param2, param3, param4, param5, param6, param7, param8

Now our guard gives us three offenses:

Rubocop Parameter Offenses

So it looks like Rubocop will complain if your method has more than 5 parameters. Looks like this preference comes from the Ruby Style Guide.

I’ll have to remember to have 4 or less parameters for any methods I create in the future.

Although, I could configure Rubocop to allow me up to 7 parameters:

# .rubocop.yml
  Max: 7

No, that’s probably a bad idea. Nevermind.

1 Comment

Comments are closed. Would you like to contact the author directly?

Copyright © 2008-2017 Jason Noble's Technical Adventures All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.2.3, from BuyNowShop.com.