Rails5 で rubocop を使ってみる
Ruby Ruby on Rails
Published: 2019-06-06

やったこと

今回、 rubocop を使ってみます。

rubocop は、static code analyzer です。(引用そのまま)

確認環境

$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]

$ rails --version
Rails 5.2.3

調査

インストールその1 (失敗)

Gemfile

gem 'rubocop', '~> 0.71.0', require: false

$ bundle install

なんかエラーが出て、gem 追加しろと言われています。

Post-install message from rubocop:
Rails cops will be removed from RuboCop 0.72. Use the `rubocop-rails` gem instead.

Put this in your `Gemfile`.


```rb
gem 'rubocop-rails'
```

And then execute:

```sh
$ bundle install
```

Put this into your `.rubocop.yml`.

```yaml
require: rubocop-rails
```

More information: https://github.com/rubocop-hq/rubocop-rails

インストールその2 (成功)

Gemfile

gem 'rubocop', '~> 0.71.0', require: false
gem 'rubocop-rails'
$ bundle install

使ってみる

ヘルプ

$ bundle exec rubocop -h

手元のファイルで実行する

$ bundle exec rubocop app/controllers/tasks_controller.rb
Inspecting 1 file
C

Offenses:

app/controllers/tasks_controller.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.
class TasksController < ApplicationController
^^^^^
app/controllers/tasks_controller.rb:1:1: C: Style/FrozenStringLiteralComment: Missing magic comment # frozen_string_literal: true.
class TasksController < ApplicationController
^
app/controllers/tasks_controller.rb:14:5: C: Style/RedundantBegin: Redundant begin block detected.
    begin
    ^^^^^
app/controllers/tasks_controller.rb:17:5: C: Style/RescueStandardError: Avoid rescuing without specifying an error class.
    rescue => e
    ^^^^^^
app/controllers/tasks_controller.rb:28:3: C: Style/EmptyMethod: Put empty method definitions on a single line.
  def new ...
  ^^^^^^^
app/controllers/tasks_controller.rb:47:12: C: Style/HashSyntax: Use the new Ruby 1.9 hash syntax.
    render :json => tmp.to_jso

C は、Convention です。

ここには載っていませんが、

W (Warning)、E (Error)、F (Fatal) とあります。

参考