• Stars
    star
    4,163
  • Rank 10,406 (Top 0.3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 15 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

a code metric tool for rails projects

rails_best_practices

Gem Version CI Coverage Status AwesomeCode Status for flyerhzm/rails_best_practices

Coderwall Endorse Click here to lend your support to: rails best practices and make a donation at www.pledgie.com !

rails_best_practices is a code metric tool to check the quality of Rails code.

It supports the following ORM/ODMs:

  • activerecord
  • mongoid
  • mongomapper

And the following template engines:

  • erb
  • haml
  • slim
  • rabl

rails_best_practices supports Ruby 1.9.3 or newer.

External Introduction

Ruby5 - Episode #253

Railscasts - #252 Metrics Metrics Metrics

Usage

At the root directory of a Rails app, run:

rails_best_practices .

Or for HTML output:

rails_best_practices -f html .

By default rails_best_practices will parse code in the vendor, spec, test and features directories.

Excluding directories

To exclude a directory simply call it with -e or --exclude:

rails_best_practices -e "db/migrate" .

To exclude multiple directories, separate them with comma:

rails_best_practices -e "db/migrate,vendor" .

Other command-line options

To see the full list of command-line options, run:

$ rails_best_practices -h

Usage: rails_best_practices [options]
    -d, --debug                      Debug mode
    -f, --format FORMAT              output format
        --without-color              only output plain text without color
        --with-textmate              open file by textmate in html format
        --with-vscode                open file by vscode in html format
        --with-sublime               open file by sublime in html format (requires https://github.com/asuth/subl-handler)
        --with-mvim                  open file by mvim in html format
        --with-github GITHUB_NAME    open file on github in html format. GITHUB_NAME is like railsbp/rails-bestpractices OR full URL to GitHub:FI repo
        --with-hg                    display hg commit and username, only support html format
        --with-git                   display git commit and username, only support html format
        --template TEMPLATE          customize erb template
        --output-file OUTPUT_FILE    output html file for the analyzing result
        --silent                     silent mode
        --vendor                     include vendor files
        --spec                       include spec files
        --test                       include test files
        --features                   include features files
    -x, --exclude PATTERNS           Don't analyze files matching a pattern
                                     (comma-separated regexp list)
    -o, --only PATTERNS              analyze files only matching a pattern
                                     (comma-separated regexp list)
    -g, --generate                   Generate configuration yaml
    -c, --config CONFIG_PATH         configuration file location (defaults to config/rails_best_practices.yml)
    -v, --version                    Show this version
    -h, --help                       Show this message

Resources

Homepage: http://rails-bestpractices.com

GitHub: http://github.com/railsbp/rails_best_practices

Team Blog http://rails-bestpractices.com

Google Group: https://groups.google.com/group/rails_best_practices

Wiki: http://github.com/railsbp/rails_best_practices/wiki

Issue Tracker: http://github.com/railsbp/rails_best_practices/issues

Install

gem install rails_best_practices

or add it to the Gemfile

gem "rails_best_practices"

--with-sublime

Install https://github.com/asuth/subl-handler

Editor Integration

TextMate 2

If you use TextMate 2, you can install the RailsBestPractices.tmbundle bundle.

Issues

If you install the rails_best_practices with bundler-installed GitHub-sourced gem, please use the following command instead.

bundle exec rails_best_practices .

If you encounter a NoMethodError exception, or a syntax error, you can use debug mode to discover which file is to blame:

rails_best_practices -d .

That will provide the error's stack trace and the source code of the file which is causing the error.

Custom Configuration

First run:

rails_best_practices -g

to generate rails_best_practices.yml file.

Now you can customize this configuration file. The default configuration is as follows:

AddModelVirtualAttributeCheck: { }
AlwaysAddDbIndexCheck: { }
#CheckSaveReturnValueCheck: { }
#CheckDestroyReturnValueCheck: { }
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: { }
UseObserverCheck: { }
#UseParenthesesInMethodDefCheck: { }
UseQueryAttributeCheck: { }
UseSayWithTimeInMigrationsCheck: { }
UseScopeAccessCheck: { }
UseTurboSprocketsRails3Check: { }

Now, at the root directory of a Rails app, run:

rails_best_practices . -c config/rails_best_practices.yml

You can remove or comment a review to disable it, and you can change the options.

You can apply the ignored_files option on any rule by giving a regexp or array of regexps describing the path of the files you don't want to be checked:

DefaultScopeIsEvilCheck: { ignored_files: 'user\.rb' }
LongLineCheck: { max_line_length: 80, ignored_files: ['db/migrate', 'config/initializers'] }

Implementation

Move code from Controller to Model

  1. Move finder to named_scope (rails2 only)
  2. Use model association
  3. Use scope access
  4. Add model virtual attribute
  5. Replace complex creation with factory method
  6. Move model logic into the Model
  7. Check return value of "save!"

RESTful Conventions

  1. Overuse route customizations
  2. Needless deep nesting
  3. Not use default route
  4. Restrict auto-generated routes

Model

  1. Keep finders on their own model (rails2 only)
  2. The law of demeter
  3. Use observer
  4. Use query attribute
  5. Remove unused methods in models
  6. Protect mass assignment
  7. Destroy return value (disabled by default)

Mailer

  1. Use multipart/alternative as content_type of email

Migration

  1. Isolating seed data
  2. Always add database index
  3. Use say with time in migrations

Controller

  1. Use before_filter (disabled by default)
  2. Simplify render in controllers
  3. Remove unused methods in controllers

Helper

  1. Remove empty helpers
  2. Remove unused methods in helpers

View

  1. Move code into controller
  2. Move code into model
  3. Move code into helper
  4. Replace instance variable with local variable
  5. Simplify render in views
  6. Not use time_ago_in_words

Deployment

  1. Dry bundler in Capistrano
  2. Speed up assets precompilation with turbo-sprockets-rails3

Other

  1. Remove trailing whitespace
  2. Remove tab (disabled by default)
  3. Hash syntax (disabled by default)
  4. Use parentheses in method definition (disabled by default)
  5. Long line (disabled by default)
  6. Not rescue exception

Write Your Own Checklist

If you want to write your own checklist (some checklist only for your Rails projects), please read this first, How to write your own check list?

Contribute

If you want to add your rails best practices into the gem, please post your best practices on http://rails-bestpractices.com

Contact Us

We provide Rails consulting services, you can contact us by Twitter or email.

Follow us on twitter: http://twitter.com/railsbp

Send us email: [email protected]

Copyright ยฉ 2009 - 2022 Richard Huang ([email protected]), released under the MIT license

More Repositories

1

bullet

help to kill N+1 queries and unused eager loading
Ruby
7,081
star
2

switch_user

Easily switch current user
Ruby
732
star
3

chinese_pinyin

translate chinese hanzi to pinyin
Ruby
430
star
4

activemerchant_patch_for_china

A rails plugin to add an active_merchant patch for china online payment platform including alipay (ๆ”ฏไป˜ๅฎ), 99bill (ๅฟซ้’ฑ) and tenpay (่ดขไป˜้€š)
Ruby
305
star
5

css_sprite

automatically css sprite
Ruby
242
star
6

uniform_notifier

uniform notifier for rails logger, customized logger, javascript alert, javascript console, growl and xmpp
Ruby
235
star
7

rails-bestpractices.com

HTML
200
star
8

redis-sentinel

another redis automatic master/slave failover solution for ruby by using built-in redis sentinel (deprecated)
Ruby
188
star
9

eager_group

fix n+1 aggregate sql functions for rails
Ruby
122
star
10

seo_checker

check your website if it is seo.
Ruby
117
star
11

simple_cacheable

a simple cache implementation for rails
Ruby
91
star
12

code_analyzer

code analyzer tool which is extracted from rails_best_practices
Ruby
86
star
13

resque-restriction

resque-restriction is an extension to resque queue system that restricts the execution number of certain jobs in a period time.
Ruby
86
star
14

rfetion

rfetion is a ruby gem for China Mobile fetion service that you can send SMS free.
Ruby
61
star
15

chinese_regions

provides all chinese regions, cities and districts
Ruby
60
star
16

mongoid-eager-loading

eager loading for mongoid (DEPRECATED)
Ruby
54
star
17

rails-brakeman.com

online security check for rails projects
Ruby
52
star
18

contactlist

java api to retrieve contact list of email(hotmail, gmail, yahoo, sohu, sina, 163, 126, tom, yeah, 189 and 139) and im(msn)
Java
49
star
19

regexp_crawler

A crawler which uses regular expression to catch data from website.
Ruby
45
star
20

chinese_permalink

This plugin adds a capability for AR model to create a seo permalink with your chinese text. It will translate your chinese text to english url based on google translate.
Ruby
41
star
21

apis-bench

Ruby
34
star
22

sitemap

This plugin will generate a sitemap.xml from sitemap.rb whose format is very similar to routes.rb
Ruby
32
star
23

twitter_connect

facebook connect style twitter oauth
Ruby
30
star
24

taobao

Ruby Client Library for Taobao Open Platform
Ruby
27
star
25

huangzhimin.com

my homepage
HTML
24
star
26

railsbp.com

railsbp.com
JavaScript
23
star
27

multiple_mailers

extend actionmailer to allow one smtp account per mailer class.
Ruby
23
star
28

contactlist-client

The contactlist-client gem is a ruby client to contactlist service which retrieves contact list of email(hotmail, gmail, yahoo, sohu, sina, 163, 126, tom, yeah, 189 and 139) and im(msn)
Ruby
20
star
29

donatecn

demo for activemerchant_patch_for_china
Ruby
17
star
30

monitor

Monitor gem can display ruby methods call stack on browser based on unroller
JavaScript
17
star
31

authlogic_renren_connect

Extension of the Authlogic library to add Renren Connect support built upon the renren plugin
Ruby
5
star
32

rails3-template

rails3 template includes a lot of useful plugins/gems
Ruby
5
star
33

nodeslide

node.js related slideshows [deprecated], move to nodeslide.heroku.com
JavaScript
4
star
34

rubyslide.com

collect ruby rails related presentations [deprecated], moved to rubyslide.heroku.com
Ruby
4
star
35

visual_partial

This plugin provides a way that you can see all the partial pages rendered. So it can prevent you from using partial page too much, which hurts the performance.
Ruby
4
star
36

codelinestatistics

The code line statistics takes files and directories from GUI, counts the total files, total sizes of files, total lines, lines of codes, lines of comments and lines of blanks in the files, displays the results and can also export results to html file.
Ruby
4
star
37

clock_chrome_extension

google chrome extension to display multiple clock analogs for multiple timezones
2
star
38

dotfiles

Vim Script
2
star
39

showoff-understanding-mongoid

My understanding mongoid showoff presentation
Ruby
2
star
40

enough_fields

only select specified fields used
Ruby
2
star
41

skype_archive

company hackathon
Ruby
1
star
42

bullet_test

Ruby
1
star
43

play_skype

JavaScript
1
star
44

test_code_analyzer

test code for code_analyzer gem
Ruby
1
star
45

blog.huangzhimin.com

HTML
1
star
46

test_error

raise an error to test if exception_notification really works.
Ruby
1
star
47

try-ripper

code mirror of try-ripper.heroku.com
CSS
1
star