Common Rubocop Errors: Improve Your Ruby Code Quality Quickly

Rubocop is a static code check tool for ruby. Very handy and powerful.

Here is a list of Common Rubocop Errors, for your reference. You can simply search by your Rubocop error message in this post. And get your code improved quickly.

Common Rubocop Errors: Improve Your Ruby Code Quality



Ruby is a frequently used glue language for DevOps. Both Chef and Puppet are implemented by Ruby. For ruby code check, I use Rubocop[1] and Foodcritic[2] frequently. For Python code, I use pylint[3]. For Shell code, I highly recommend shellcheck.

Tips: Create Jenkins jobs to run periodical check for all your scripts.

Here are samples in Github: Ruby, Python and Bash. GitHub

I also maintain a free and available demo Jenkins here.

1.1 Use Latest Stable Version Of Rubocop

Latest version has a lot of new checks enforced. Make sure your ruby is no older than 2.2.5. Upgrade your Rubocop to the latest version you can get. Then stick to that version.

Tips For Package Installation: Always install latest versions could be troublesome.

# Install rubocop
gem install rubocop

# Update rubocop
gem update rubocop

1.2 Rubocop Skip Certain Files Or Rules

Customize .rubocop.yml like below.

AllCops:
  Excludes:
    - Berksfile
    - recipes/basic.rb
    - attributes/*.rb

# Customize rules
Metrics/LineLength:
  Max: 95

MethodLength:
  Max: 35

Metrics/AbcSize:
   Enabled: false

BlockLength:
  Max: 70

Below is a list of Rubocop Common Error Messages and Corrections.

Okay, you can stop reading and now. Press Ctrl + F, then search by error messages.

1.3 Rubocop Error: Use 0o for octal literals

See Official Link. mode 0700 -> mode 0o700

  • Error Message:
recipes/basic.rb:24:8: C: Use 0o for octal literals.
  mode 0700
       ^^^^
  • From:
template '/opt/app/logback.xml' do
  source 'logback.xml.erb'
  mode 0700
end

  • To:
template '/opt/app/logback.xml' do
  source 'logback.xml.erb'
  mode 0o700
end

You can also ignore the rule, by changing .rubocop.yml. (Thanks to Jack Lee).

Style/NumericLiteralPrefix:
    EnforcedOctalStyle: zero_only

1.4 Rubocop Error: C: Prefer single-quoted strings

  • Error Message:
recipes/precheck.rb:28:23: C: Prefer single-quoted strings when you don't need string interpolation or special symbols.
  • From:
if disk['mount'] == "/" && disk.has_key?('kb_available')
                    ^^^
  • To:
if disk['mount'] == '/' && disk.has_key?('kb_available')

1.5 Rubocop Error: C: Use \ instead of + or << to concatenate those strings.

  • Error Message:
recipes/basic.rb:36:67: C: Use \ instead of + or << to concatenate those strings.
"http://#{node['my_couchbase']['repo_server']}/couchbase-server" + \
                                                                  ^
recipes/basic.rb:37:47: C: Use \ instead of + or << to concatenate those strings.
"-#{node['couchbase']['server']['edition']}_" + \
                                              ^
  • From:
node.default['couchbase']['server']['package_full_url'] = \
"http://#{node['my_couchbase']['repo_server']}/couchbase-server" + \
"-#{node['couchbase']['server']['edition']}_" + \
"#{node['couchbase']['server']['version']}-ubuntu12.04_amd64.deb"
  • To:
node.default['couchbase']['server']['package_full_url'] = \
"http://#{node['my_couchbase']['repo_server']}/couchbase-server" \
"-#{node['couchbase']['server']['edition']}_" \
"#{node['couchbase']['server']['version']}-ubuntu12.04_amd64.deb"

1.6 Rubocop Error: C: Redundant return detected.

  • Error Message:
serverspec/server_spec.rb:21:3: C: Redundant return detected.
  return " -p devops_branch_name=#{devops_branch_name}"
  ^^^^^^
  • From:
def build_parameter_updatejenkins(devops_branch_name)
  return " -p devops_branch_name=#{devops_branch_name}"
end
  • To:
def build_parameter_updatejenkins(devops_branch_name)
  " -p devops_branch_name=#{devops_branch_name}"
end

1.7 Rubocop Error: C: Hash#haskey? is deprecated in favor of Hash#key?.

  • Error Message:
recipes/precheck.rb:28:35: C: Hash#has_key? is deprecated in favor of Hash#key?.
  • From:
if disk['mount'] == "/" && disk.has_key?('kb_available')
                                ^^^^^^^^
  • To:
if disk['mount'] == "/" && disk.key?('kb_available')

1.8 Rubocop Error: chef onlyif/notif avoid grep command

  • Error Message:
chef only_if/not_if avoid grep command
  • From:
execute 'Fix MySQL init.d script to sleep longer' do
  cwd '/etc/init.d'
  command 'patch -p0 mysql < /tmp/mysql_init.patch'
  action :run
  only_if "grep 'sleep 1' /etc/init.d/mysql"
end
  • To:
execute 'Fix MySQL init.d script to sleep longer' do
  cwd '/etc/init.d'
  command 'patch -p0 mysql < /tmp/mysql_init.patch'
  action :run
  only_if do
    File.read('/etc/init.d/mysql').match(/sleep 1/)
  end
end

1.9 Rubocop Error: C: Use snakecase for source file names.

  • Error Message:
recipes/github-key.rb:1:1: C: Use snake_case for source file names.
#
^
  • Rename github-key.rb to githubkey.rb

1.10 Rubocop Error: C: Block has too many lines

  • Error Message:
recipes/nagios_client.rb:75:1: C: Block has too many lines. [37/25]
node['common_basic']['service_list'].each do |service| ...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
recipes/nagios_server.rb:39:1: C: Block has too many lines. [53/25]
node['common_basic']['service_list'].each do |service| ...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  • Fix: Update .rubocop.yml with workaround. Or cut your code into small chunks.
# .rubocop.yml
BlockLength:
  Max: 90

1.11 Rubocop Error: C: Use the return of the conditional

See official link.

  • Error Message:
files.rb:1:1: C: Use the return of the conditional for variable assignment and comparison.
if node['my_app']['enable_remotehost'] == '' ...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  • From:
if node['my_app']['enable_remotehost'] == ''
  logback_remotehost = node['my_app']['server1_hosts'][0]
else
  logback_remotehost = node['my_app']['master_host']
end

To:

logback_remotehost = if node['my_app']['enable_remotehost'] == ''
                       node['my_app']['server1_hosts'][0]
                     else
                       node['my_app']['master_host']
                     end

1.12 Rubocop Error: C: Use a guard clause instead of wrapping the code conditionally

See official link.

  • Error Message:
serverspec/general_helper.rb:67:7: C: Use a guard clause instead of wrapping the code inside a conditional expression.
      if item == skip_item
      ^^

From:

loop do
  break if item != skip_item
  item = list_get_random_item(list)
end

To:

loop do
  if item == skip_item
    item = list_get_random_item(list)
  else
    break
  end
end

1.13 Rubocop Error: C: Separate every 3 digits in the integer portion

  • Error Message:
files.rb:2:8: C: Separate every 3 digits in the integer portion of a number with underscores(_).
  port 48080
       ^^^^^
  • From:
firewall_rule 'port_list_allowall' do
  port 48080
  protocol :tcp
  position 1
  action :allow
end

  • To:
firewall_rule 'port_list_allowall' do
  port 48_080
  protocol :tcp
  position 1
  action :allow
end

1.14 Rubocop Error: C: Freeze mutable objects assigned to constants.

  • Error Message:
vagrant/Vagrantfile:7:16: C: Freeze mutable objects assigned to constants.
FOLDER_SHARE = 'local_code_share'
               ^^^^^^^^^^^^^^^^^^
  • From:
FOLDER_SHARE = 'local_code_share'

  • To:
folder_share = 'local_code_share'

1.15 Rubocop Error: C: Closing array brace must be on the line…

See official link.

  • Error Message:
files.rb:3:39: C: Closing array brace must be on the line after the last array element when opening brace is on a separate line from the first array element.
  /opt/devops/logs /opt/devops/plugins).each do |x|
                                      ^
  • From:
%w(
  /opt/devops /opt/devops/bin /opt/devops/config /opt/devops/config/env.d
  /opt/devops/logs /opt/devops/plugins).each do |x|
  directory x do
    owner 'root'
    group 'root'
    mode 0o755
    action :create
  end
end
  • To:
%w(
  /opt/devops /opt/devops/bin /opt/devops/config /opt/devops/config/env.d
  /opt/devops/logs /opt/devops/plugins
).each do |x|
  directory x do
    owner 'root'
    group 'root'
    mode 0o755
    action :create
  end
end

1.16 Rubocop Error: C: Use Kernel#loop for infinite loops

See official link

test/shared/common_spec_helper.rb:32:5: C: Use Kernel#loop for infinite loops.
    while true
    ^^^^^
test/shared/common_spec_helper.rb:32:11: W: Literal true appeared in a condition.
    while true
          ^^^^
  • From:
while true
  if item == skip_item
    item = list_get_random_item(list)
  else
    break
  end
end

  • To:
loop do
  break if item != skip_item
  item = list_get_random_item(list)
end

[1] http://batsov.com/rubocop/
[2] http://acrmp.github.io/foodcritic/
[3] https://www.pylint.org

More Reading:

linkedin
github
slack

PRs Welcome

Blog URL: https://www.dennyzhang.com/rubocop_errors


3 Responses to Common Rubocop Errors: Improve Your Ruby Code Quality Quickly

  1. for this error message: Rubocop Error: Use 0o for octal literals
    Add ignore rule to .rubocop.yml would be better because these numbers are not octal literals.

    Style/NumericLiteralPrefix:
    EnforcedOctalStyle: zero_only

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.