We’d like to introduce you a static analytical tool for Ruby called RuboCop.
You can use the automatic code review function of RuboCop even in Sider now. This is a good opportunity for you to try out RuboCop, why not!?
This introduces RuboCop, RuboCop’s Rails option, lint option which detects the contents that cause bugs, and other options which are useful for other than rules, please take your time to read!
Table Of Contents
- What is RuboCop
- Benefits for using RuboCop
- RuboCop installation
- RuboCop basics
-R(--rails)
option-l(--lint)
option- How to write
.rubocop.yml
file - How to use
.rubocop_todo.yml
-a(--auto-correct)
option- Example of
.rubocop.yml
What is RuboCop
RuboCop is a static code analyzing tool to check whether the ruby code in your project “is written as per the coding rules”.
The default coding rules are based on Ruby style guide.
(Japanese version)
By editing the configuration file (.rubocop.yml
), you can add or delete your own coding rules.
Benefits for using RuboCop
The setting of Rubocop is collated in the .rubocop.yml
file, then it clearly indicates the project coding rules.
By using Rubocop to keep the codes clean, you’ll have less mistakes and it leads to effective review.
RuboCop installation
RuboCop is provided via gem.
When you use Bundler, add below into the Gemfile.
gem 'rubocop', require: false
In case of web applications such as rails,
Since most of the case they are executed in the development environment, followings are sufficient.
group 'development' do
...
gem 'rubocop', require: false
end
You can install
$ bundle
after editing the GemFile.
In case you don’t use Bunfler, you can install it in $ gem install rubocop
.
RuboCop basics
The description prior to this part has been verified by using the following versions.
- ruby 2.2.0p0 (2014–12–25 revision 49005) [x86_64-darwin14]
- rubocop 0.29.1
rubocop
commands
Execute commands are as follows.
In case of using Bundler, kindly add bundle exec
in the top.
$ rubocop [options] [file1, file2, ...]
- In order to verify all ruby files in the project, simply follow the below.
$ rubocop
- To refer to the Help, kindly follow the below.
$ rubocop --help
rubocop
execution – interpretation of output results
For example, prepare a ruby file (test.rb
) as shown below.
def badName
if something
test
end
end
Execute RuboCop for this test.rb
.
$ rubocop test.rb
Output would be as follows.
Inspecting 1 file
W
Offenses:
test.rb:1:5: C: Use snake_case for method names.
def badName
^^^^^^^
test.rb:2:3: C: Use a guard clause instead of wrapping the code inside a conditional expression.
if something
^^
test.rb:2:3: C: Favor modifier if usage when having a single-line body. Another good alternative is the usage of control flow &&/||.
if something
^^
test.rb:4:5: W: end at 4, 4 is not aligned with if at 2, 2
end
^^^
1 file inspected, 4 offenses detected
The output above can be interpreted as follows.
Inspecting 1 file
in the first line indicates the number of verified ruby files.- The
W
in the second line indicates the first letter of the most severe violation (sort byConvention
,Warning
,Error
,Fatal
severity levels ) that was found in the verified ruby files.
4 violations have been found in this example, the most severe violation wasWarning
. HenceW
has been output.. - For the 3rd line and later show detailed location for respective violation (file name: row: column) and description of the violations.
- The last line shows the number of verified files and the number of violations
Let’s have a look the output when all the violations have been fixed.
def good_name test if something end
$ rubocop test.rb
Inspecting 1 file
.
1 file inspected, no offenses detected
no offenses detected
, it means coding violation is now 0.
R(--rails)
option
For rails projects, by adding -R option for execution, it executes Rails Cop(special Cop in rails) additionally.
There are no coding violations found in the following ruby( test.rb
) file using the default RuboCop,
def good_name
puts 'test' if something
end
but by placing it under app/models
of rails and executing it with the -R
option, it shows
$ rubocop -R app/models/test.rb
Inspecting 1 file
C
Offenses:
app/models/test.rb:2:3: C: Do not write to stdout. Use Rails' logger if you want to log.
print 'test' if something
^^^^^
1 file inspected, 1 offense detected
As you see, it outputs Rails specific violation “Use Rails logger rather than the standard output”.
Rails Cop is defined in gem’s lib/rubocop/cop/ below rails .
Moreover, by setting the followings in .rubocop.yml
file,
AllCops: RunRailsCops: true
you can keep Rails Cop enabled which is same as specifying the -R option.
l( — lint) option
The verification rules (Cop) in RuboCop are classified into below 4 items.
- Style (Cop for style)
- Lint (Cop for high error possibility area or bad practice)
- Metrics (Cop for the number of class row or the number of characters in a line)
- Rails (Special Cop for Rails)
The -l
option only Lint.
How to write .rubocop.yml file
By placing the configuration file .rubocop.yml in the root directory of the project, RuboCop will read this automatically. Or it can also specify a yml file in any location as configuration file by -c option.
Below are the representative codes in .rubocop.yml file.
Specify the file to exclude from RuboCop
Use Exclude:
to exclude files like (db/schema.rb
) which is automatically generated by Rails,
or gem placed under vendor/bundle
from RuboCop.
For example, use the followings to exclude the db/schema.rb
file from RuboCop.
AllCops:
Exclude:
- db/schema.rb
However, by doing this, Exclude which is configured by default will be disabled.
Hence if you would like to continue to use 'vendor/**/*'
which is default exclude, you can write as below.
AllCops: Exclude: - db/schema.rb - 'vendor/**/*'
Reference: The one important thing to use rubocop gem
Enabling/Disabling Cop (Enabled: false/true)
When you feel a certain cop isn’t suitable for the project, you can disable it individually.
For example, there is a Cop named Style/StringLiterals
.
This rule indicates that 「Always use single quotes for the literals of string that variables expansion is not required」.
To disable this, set Enabled: false
after the Cop name.
Style/TrailingComma:
Enabled: false
Setting example for Cop with option
Some Cop have configurable parameter ( Configuration parameters
) .
For instance, the previous Style/StringLiterals
Cop has 2 options for the literals of String that doesn’t require variable expansion. One is always use single quotes (default), or always use double quotes.
EnforcedStyle: single_quotes # default
EnforcedStyle: double_quotes
Although the default is single_quotes
, if you prefer double_quotes
you can set as shown below.
Style/StringLiterals:
EnforcedStyle: double_quotes
Other settings
There are other default rules in the config/default.yml(github source)
of the rubocop gem..
How to use .rubocop_todo.yml
If you have too many violations that need to be fixed, there is a method to generate the .rubocop_todo.yml
file and use it as a TODO list.
.rubocop_todo.yml
can be easily generated by using --auto-gen-config
option.
Recreate the test.rb
using the following.
def badName
if something
test
end
end
Then, execute rubocop with the --auto-gen-config
option.
$ rubocop --auto-gen-config test.rb
It generates the file .rubocop_todo.yml
Contents will be as follows.
$ cat .rubocop_todo.yml
# This configuration was generated by `rubocop --auto-gen-config`
# on 2015-03-09 19:07:44 +0900 using RuboCop version 0.29.1.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 1
# Configuration parameters: SupportedStyles.
Lint/EndAlignment:
AlignWith: variable
# Offense count: 1
# Configuration parameters: MinBodyLength.
Style/GuardClause:
Enabled: false
....
This yml file has the same format as the .rubocop.yml
file, and it outputs the configuration which disables the violating Cops.
Call the generated file from .rubocop.yml
inherit_from: .rubocop_todo.yml
Based on this
You can distinguish
- 「rules to follow」 which is
.rubocop.yml
file
and
- 「violations to be fixed」 which is
.rubocop_todo.yml
file.
When you start fixing the violations, you better fix by deleting items in .rubocop_todo.yml one by one.
-a( — auto-correct) option
For some violations, by executing rubocop by adding -a
option, the codes will fix automatically.
Cop supports --auto-correct
is written on items that support auto-correct located in the .rubocop_todo.yml
which is generated with the --auto-gen-config
option.
However, this function is in the experimental stage, you need to take care.
.rubocop.yml example
Here is the examples of open source .rubocop.yml
- BBC-News/rubocop-config
- https://github.com/BBC-News/rubocop-config/blob/master/.rubocop.yml
- Configuration file which is uploaded by the British Broadcasting Corporation BBC in GitHub.
- thoughtbot/hound
- https://github.com/thoughtbot/hound/blob/master/config/style_guides/ruby.yml
- This is a configuration file committed in the Rails application of the automated review service 「hound」 operated by the thoughtbot company.
- thoughtbot also publishes style guide and it might also be interesting to compare with this.
- spree/spree
- https://github.com/spree/spree/blob/master/.rubocop.yml
- spree is a Rails application for open source EC site.
Summary
You can use RuboCop via SideCI. When you open or update a Pull Request in GitHub, RuboCop will be automatically run in SideCI and it will provide comments in the Pull Request.
If you do not customize the .rubocop.yml
file, the RuboCop standard setting will be used to perform the analysis. Moreover, if the project is Rails, SideCI will determine whether this is Rails or not automatically and execute RuboCop by -R
option for Rails.
Please have a try our SideCI.
More articles about RuboCop
- Using RuboCop for quick automated code reviews with Docker
- Use RuboCop to check the conformity of your Ruby code with the style guide
- Analyzing code with RuboCop on a Ruby on Rails project
- Extract Hidden Coding Styles to .rubocop.yml with Gry
- Let’s start using RuboCop! The release of MeowCop, the best configs for introducing RuboCop!
- Educate RuboCop, try out rubocop.yml which prioritize the speed to the rules
For more information about Sider, please go to our website.