代码质量控制,是项目自始至终都应该去掌控的事情。 虽然每个团队的风格总会有一些出入,但是达成共识是一件并不困难的事情。 达成共识以后,我们需要借助工具,以及达成一套流程来帮助我们半自动化或自动化地做这样的一件事情。
在 Ruby 社区里,目前最广泛使用的是 Rubocop 。
Rubocop 是一个 Ruby 静态代码分析。 其默认遵循的是一个由社区驱动的 Ruby Style Guide 。
在 Gemfile 增加
group :develop do gem 'rubocop', require: false end
运行
bundle install bundle exec rubocop
每个团队的风格不一样,一定会有自定义的需求,只需要 Rails 项目根目录下,新建文件
.rubocop.yml
AllCops: Exclude: - 'vendor/**/*' - 'spec/fixtures/**/*' - 'tmp/**/*' TargetRubyVersion: 2.1 Style/Encoding: EnforcedStyle: when_needed Enabled: true Style/FrozenStringLiteralComment: EnforcedStyle: always Style/IndentHeredoc: EnforcedStyle: powerpack Metrics/BlockLength: Exclude: - 'Rakefile' - '**/*.rake' - 'spec/**/*.rb'
如果想要自定义,可以参考文件 https://github.com/bbatsov/rubocop/blob/master/config/default.yml
然后在 .rubocop.yml
添加即可。
.rubocop.yml
inherit_from: .rubocop_todo.yml AllCops: Include: - '**/Gemfile' - '**/Rakefile' Exclude: - 'bin/*' - 'db/migrate/*' - 'db/seeds.rb' - 'db/schema.rb' - 'vendor/bundle/**/*' - 'script/**/*' - !ruby/regexp /old_and_unused/.rb$/ TargetRubyVersion: 2.1 Documentation: Enabled: false Style/AsciiComments: Enabled: false Style/MethodDefParentheses: # EnforcedStyle: require_no_parentheses_except_multiline EnforcedStyle: require_parentheses # SupportedStyles: # - require_parentheses # - require_no_parentheses # - require_no_parentheses_except_multiline Metrics/LineLength: Max: 1200 Metrics/ClassLength: Max: 1200 Metrics/MethodLength: Max: 1200 Metrics/ModuleLength: Max: 1200
.rubocop_todo.yml
# This configuration was generated by # `rubocop --auto-gen-config` # on 2016-04-19 10:48:45 +0800 using RuboCop version 0.39.0. # 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: 25 # Configuration parameters: AllowHeredoc, AllowURI, URISchemes. # URISchemes: http, https Metrics/LineLength: Max: 120 # Offense count: 5 Style/AsciiComments: Exclude: - 'Gemfile' # Offense count: 1 # Cop supports --auto-correct. Style/BlockComments: Exclude: - 'spec/spec_helper.rb' # Offense count: 3 Style/Documentation: Exclude: - 'spec/**/*' - 'test/**/*' - 'app/controllers/application_controller.rb' - 'app/helpers/application_helper.rb' - 'config/application.rb' # Offense count: 1 # Cop supports --auto-correct. # Configuration parameters: AllowForAlignment, ForceEqualSignAlignment. Style/ExtraSpacing: Exclude: - 'bin/setup' # Offense count: 3 # Cop supports --auto-correct. # Configuration parameters: SupportedStyles. # SupportedStyles: call, braces Style/LambdaCall: EnforcedStyle: braces # Offense count: 20 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles, ConsistentQuotesInMultiline. # SupportedStyles: single_quotes, double_quotes Style/StringLiterals: Enabled: false