12
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RuboCopエラー対応(Layout/EmptyLineAfterGuardClause)

Last updated at Posted at 2018-09-27

はじめに

Rails(Ruby)環境でコーディングをしていた際に、RuboCopでこんなエラーが出ました。

一部抜粋 & 編集

app/decorators/file_name.rb:63:5: C: Layout/EmptyLineAfterGuardClause: Add empty line after guard clause.
    return something if method.nil?
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

RuboCop とは?

Rubyのコードを整形してくれるやつです。

RuboCop is a Ruby static code analyzer and code formatter

自分が今回書いたコードの中身は、早期リターンを入れたelse付きの後置if文です。

def method_name
  return "something" if method_A.nil?
  method_B(引数)
end

コードの内容は単純で、method_A の中身が nil だったら文字列 "something" を返し、そうじゃなければ、method_B(引数)を実行する。という内容です。

早期returnとは?

あまり起きないケース、あるいは重要でないケースでifのネストを深くしたり、else句を使うのを避けるためのテクニックです。

引用
https://qiita.com/n_slender/items/e062454114facd00a942

RuboCopのエラーメッセージとその内容

上記コードでも動くのですが、RuboCop 的には正しくありません。

その時のエラー文が

app/decorators/file_name.rb:63:5: C: Layout/EmptyLineAfterGuardClause: Add empty line after guard clause.
    return something if method.nil?
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

でした

どう対応したか?

以下のようにコードを書き換えました。

def method_name
  return "something" if method_A.nil?

  method_B(引数)
end

なぜ、こう対応したか?

エラー文

Layout/EmptyLineAfterGuardClause

で、ググると、RuboCopの公式ドキュメントが出てきます。

参考
https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Layout/EmptyLineAfterGuardClause

このページのOverviewには下記のように書いてあります。

This cop enforces empty line after guard clause

「このコップ(警察)は、ガード節の後には空行を必ずいれとけ」と、言っています。

なので、空行を入れました。

ガード節とは?

処理の対象外とする条件を関数やループの先頭に集め、早めに return や continue/break で抜ける方法です。ネストを減らし異常系と正常系の処理がわかりやすくなるメリットがあります。

引用
https://qiita.com/kouyan/items/7b8b456b626447a1e24e

スクリーンショット 2018-09-27 17.23.08.png

なので、ガード節の下に空行入れました!

今日は以上です!

参考

12
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?