Introduction / Recommendation configuration on Rails Best Practices to modernize Ruby on Rails…

We will introduce you how to use and the recommending configuration of gem and rails_best_practices which tell us the best practice of Rails.

rails_best_practices is a tool which collates the postings in Rails Best Practices where people vote for the best practice of Rails, and verify the codes by following the postings then provide advices how to modify.

Please have a try and if you like you can use on SideCI continuously.

Table Of Contents

  • What is rails_best_practices
  • Customizing with yml
  • Recommended yml

What is rails_best_practices

rails_best_practices is a metrics tool that checks the quality of codes in the rails application.

Unlike rubocop, it can verify the code quality specially for rails

The following description has been confirmed with the following versions.

  • MacOSX 10.10.1
  • ruby 2.2.1p85 (2015–02–26 revision 49769) [x86_64-darwin14]
  • rails_best_practices 1.15.7

Example of the verification

This is an example of the verification.

The db/schema.rb has been set with the following content.

ActiveRecord::Schema.define(version: 20131103153637) do
create_table "book_authors", force: true do |t|
t.integer "book_id"
t.integer "author_id"
t.datetime "created_at"
t.datetime "updated_at"
create_table "books", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
create_table "authors", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"

With this, the external key of table book_authors does not have an index.
This is an in violation with the rule defined in the rails_best_practices Always add DB index.
The rails_best_practices command will be able to detect this as a violation.

$ rails_best_practices db/schema.rb
Source Codes: |====================================================================================|
/Users/me/repos/homework/db/schema.rb:16 - always add db index (book_authors => [book_id])
/Users/me/repos/homework/db/schema.rb:16 - always add db index (book_authors => [author_id])
Please go to to see more useful Rails Best Practices.
Found 2 warnings.

It detected as always add db index.
rails_best_practices has several items specialized for reails such as above (41 definitions in version1.15).
You can visit rails_best_practices website for the most of items.

rails_best_practices installation

rails_best_practices is provided by gem.
When using Bundler, please add

gem ‘rails_best_practices’, require: false

in the Gemfile.
After modifying Gemfile, you can install it by using

$ bundle

If you are not using Bundler, you can install with $ gem install rails_best_practices.

Basic usage

The executing command is as follows.
When you are using Bundler, please add bundle exec in the top.

$ rails_best_practices [options] path

Output results in html

We are going to output it by html format not by standard output.
Please go to the directory of rails application which you are using.

$ rails_best_practices -f html .

You can specify the output format with the -f(--format) option.
The rails_best_practices_output.html file will be generated upon execution.
Open it in a browser.

$ open rails_best_practices_output.html
rails_best_practices output

By selecting Check all, the contents of the warning area(File Name(Filename), corresponding violation row number(Line Number), and warning messages (Warning Messages) will be displayed.
The warning messages(Warning Messages) are linked to the rails_best_practices website and links to a description page of the warning message.
This is written in simple English.

Customizing with yml
Configuration file

You can change the items to verify or arrange the options by modifying the configuration file( config/rails_best_practices.yml).
You can generate the configuration file template by using the -g(--generate) option to start.

$ rails_best_practices -g

The content is similar to the following yml. For the entire codes, please check it here.

AddModelVirtualAttributeCheck: { }
AlwaysAddDbIndexCheck: { }
#CheckSaveReturnValueCheck: { }
DefaultScopeIsEvilCheck: { }
DryBundlerInCapistranoCheck: { }
UseTurboSprocketsRails3Check: { }

You can enable or disable the rules by comment in or comment out.
Moreover, by using the ignored_files option notation, you can specify the files where the rules will not be applied.

DefaultScopeIsEvilCheck: { ignored_files: ‘user.rb’ }

By doing this the rule “DefaultScopeIsEvilCheck” won’t be applied for user.rb. Moreover,

LongLineCheck: { max_line_length: 80, ignored_files: [‘db/migrate’, ‘config/initializers’] }

it is also possible to pass an array by directory paths.

Recommended Settings

Here, we are providing the recommended rails_best_practices.yml in below.


AddModelVirtualAttributeCheck: { }
AlwaysAddDbIndexCheck: { }
#CheckSaveReturnValueCheck: { }
DefaultScopeIsEvilCheck: { }
DryBundlerInCapistranoCheck: { }
#HashSyntaxCheck: { }
IsolateSeedDataCheck: { }
KeepFindersOnTheirOwnModelCheck: { }
LawOfDemeterCheck: { }
#LongLineCheck: { max_line_length: 80 }
MoveCodeIntoControllerCheck: { }
MoveCodeIntoHelperCheck: { array_count: 3 }
MoveCodeIntoModelCheck: { use_count: 2 }
MoveFinderToNamedScopeCheck: { }
MoveModelLogicIntoModelCheck: { use_count: 4 }
NeedlessDeepNestingCheck: { nested_count: 2 }
NotRescueExceptionCheck: { }
NotUseDefaultRouteCheck: { }
NotUseTimeAgoInWordsCheck: { }
OveruseRouteCustomizationsCheck: { customize_count: 3 }
ProtectMassAssignmentCheck: { }
RemoveEmptyHelpersCheck: { }
#RemoveTabCheck: { }
#RemoveTrailingWhitespaceCheck: { }
#RemoveUnusedMethodsInControllersCheck: { except_methods: [] }
RemoveUnusedMethodsInHelpersCheck: { except_methods: [] }
RemoveUnusedMethodsInModelsCheck: { except_methods: [] }
ReplaceComplexCreationWithFactoryMethodCheck: { attribute_assignment_count: 2 }
ReplaceInstanceVariableWithLocalVariableCheck: { }
RestrictAutoGeneratedRoutesCheck: { }
SimplifyRenderInControllersCheck: { }
SimplifyRenderInViewsCheck: { }
#UseBeforeFilterCheck: { customize_count: 2 }
UseModelAssociationCheck: { }
UseMultipartAlternativeAsContentTypeOfEmailCheck: { }
#UseParenthesesInMethodDefCheck: { }
UseObserverCheck: { }
UseQueryAttributeCheck: { }
UseSayWithTimeInMigrationsCheck: { }
UseScopeAccessCheck: { }
UseTurboSprocketsRails3Check: { }

It almost adopst default configurations but disabling only below 2 by comment out.

Disable RemoveTrailingWhitespaceCheck

#RemoveTrailingWhitespaceCheck: { }

This rule is ”there should be no trailing spaces at the end of each row”, but this rule is not only for rails, and a tool such as rubocop can be used instead, we think it can be omitted.

Disable RemoveUnusedMethodsInControllersCheck

#RemoveUnusedMethodsInControllersCheck: { except_methods: [] }

This rule is ”methods not used in the Controller should be removed”, but since it has higher possibility of wrong judgments when configuring the route in routes.rb dynamically, we think its better omit.
Other than above two, RemoveUnusedMethodsInHelpersCheck and RemoveUnusedMethodsInModelsCheckmay have wrong judgments.
We recommend disabling or commenting out partially in ignored_files option, if it has many wrong judgments in your initial trial.
The UnusedMethods types are difficult to find where those are called due to the nature of Ruby, and there seems to be a lot of wrong judgments now. There is a case such as deleting this wrong judgment but later you’ll be in trouble. You can enable UnusedMethods type when the project is clear but if it’s not we recommend enabling and verifying also by yourself.
Please download the recommended configurations here.

Please download the version that disabled all UnusedMethods types.


Issues with rails_best_practices

We also introduce some of the issues.. Because the analysis in rails_best_practices is complicated, sometimes the gem of rails_best_practices doesn’t run properly (abnormal termination or Process freeze)..
We’ve also come across the case that by disabling the options such as RemoveUnused types, it runs. Since it finds the unused codes by looping whole project codes, the bug may exist here 
We recommend this to be disabled.


So how did you find it?
In this entry, we talked about how to use the gem called rails_best_practices to modernize the codes in Ruby on Rails and that configuration example and the reason.
If you would like to use continuously, or would like to install for your team, or would like to write codes with taking care of best practice of Rails, why not try this rails_best_practices in Sider!
This is the only web service that can review codes automatically by GitHub Pull Request x rails_best_practices. (as of posting this article)

For more information about Sider, please go to our website.

Aki Asahara

CEO of Sider. Aki joined Fixstars in 2008 and served major clients such as the US Airforce, MIT, USC, Toyota, and Hitachi High-technologies. After his successful tenure, he was appointed CEO of US operations in 2012. He was appointed CEO of Sider in 2019. He holds a Ph.D. in Astrophysics from Kyoto University and is a Certified Scrum Master.

Leave a Reply

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