コーディング規約チェッカーを使ってみたけどこの規約いけ好かない
class ClassName def method_name do_something if condition collection.map {|item| item.change.action param, hash: option } end protected def protected_method(x, y) if condition function x, y else function x + 2, y end end
普段こんな感じで書いているのですが、
rubocopさんに「[].map{|i| }の{と|の間空けてね」って言われてるんだけどなんかアレで空けたくない(
— ゆうなんとか@初段3曲落ち (@yuu_hara) 2013, 12月 10
今回はコーディング規約をチェックしてくれるrubocopというgemを紹介してもらいました。たいていのエディターごとに対応するプラグインを誰かが作っているのでgem installしておくとよさそうです。
つかいかた
rubocop [オプション] [検査対象]
対象を省略するとカレントディレクトリ以下の*.rbというファイルが検査対象になります。検査が終わると「ここがあかん」と結果を教えてくれます。ちなみにある程度コードがあるRailsのプロジェクトでやると500とか700とかのオーダーで「ここがあかん」と言ってくれます。
db/schema.rb:183:80: C: Line is too long. [89/79] add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree ^^^^^^^^^^ db/schema.rb:184:13: C: Prefer single-quoted strings when you don't need string interpolation or special symbols. add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree ^^^^^^^ db/schema.rb:184:23: C: Prefer single-quoted strings when you don't need string interpolation or special symbols. add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree ^^^^^^^^^^^^^^^^^^^^^^ db/schema.rb:184:54: C: Prefer single-quoted strings when you don't need string interpolation or special symbols. add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ db/schema.rb:184:80: C: Line is too long. [119/79] add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
ちなみにこれはほぼ自動生成した某Railsアプリに対してあった550ほどある違反のほんの一部です。このようにデフォルトだと自動生成されたものであろうとコメントであろうと容赦なく切り捨てるストロングスタイルのジャッジをしてくれます。しかし、--auto-gen-configというオプションをつけてあげると違反したルールの一覧が出力され、このファイルを「.rubocop.yml」という名前でプロジェクトのルートに置いてあげると、一転して黙ってしまいます。既存のコードがたくさんあって、手に負えないときはとりあえず黙らせて、少しずつルールの一覧から無効化するものを削除しつつ改修していくといいと思います。もしくは「ここは我が道を行くんだ」というところを決めておくかですね。私の場合は少なくとも自動生成されたものをのぞいては冒頭のように書いていきたい所存です…が、デフォルトだといくつかおこられるところがあります。もうね…