LoginSignup
159
149

More than 5 years have passed since last update.

Rubocopチートシート

Last updated at Posted at 2016-04-09

Lint

Lint::AmbiguousOperator

括弧なしのメソッド呼び出しの最初の引数であいまいな演算子のチェック

array = [1, 2, 3]

# The `*` is interpreted as a splat operator but it could possibly be
# a `*` method invocation (i.e. `do_something.*(array)`).
do_something *array

# With parentheses, there's no ambiguity.
do_something(*array)

Lint::AmbiguousRegexpLiteral

括弧なしのメソッド呼び出しの最初の引数であいまいな正規表現リテラルのチェック

# This is interpreted as a method invocation with a regexp literal,
# but it could possibly be `/` method invocations.
# (i.e. `do_something./(pattern)./(i)`)
do_something /pattern/i

# With parentheses, there's no ambiguity.
do_something(/pattern/i)

Lint::AssignmentInCondition

条件式と同時に変数代入するようなとき

if a = "hoge"
  puts a
end

Lint::BlockAlignment

endの位置が適切かブロックをチェック

variable = lambda do |i|
  i
end

Lint::DuplicatedKey

hashのkeyが重複しているかをチェック

hash = { food: 'apple', food: 'orange' }

Lint::ParenthesesAsGroupedExpression

呼び出されたメソッドの名前と左括弧の間にスペースをチェック

puts (x + y)

Lint::UnusedBlockArgument

未使用の引数をチェック

do_something do |used, unused, _unused_but_allowed|
  puts used
end

Lint::UselessAssignment

スコープ内の無駄なローカル変数の割り当てをチェック

def count(num)
  count = num + 1
end

Metrics

Metrics::AbcSize

ABC Sizeについて

Metrics::LineLength

1行あたりの長さ

Metrics::MethodLength

メソッドの長さ

Metrics::ParameterLists

パラメータの最大数

Metrics::PerceivedComplexity

メソッドの複数さを数値化したものを計算しチェック

def my_method                   # 1
  if cond                       # 1
    case var                    # 2 (0.8 + 4 * 0.2, rounded)
    when 1 then func_one
    when 2 then func_two
    when 3 then func_three
    when 4..10 then func_other
    end
  else                          # 1
    do_something until a && b   # 2
  end                           # ===
end                             # 7 complexity points

Style

Style::AccessModifierIndentation

アクセス修飾子(public/protected/private)のインデントをチェック

Style::AccessorMethodName

アクセサメソッドの名前チェック(get_/set_)

# bad
def set_attribute(value) ...

# good
def attribute=(value)

# bad
def get_attribute ...

# good
def attribute ...

Style::AlignHash

複数行のHashの場合、整列されてるかをチェック

Style::AlignParameters

複数行のメソッドの整列をチェック

Style::AsciiComments

non-ascii(英語以外)のコメントをチェック

Style::BlockDelimiters

1行に複数ブロックが含まれているかチェック

Style::BlockEndNewlin

各ブロックのendの位置をチェック

# bad
blah do |i|
  foo(i) end

# good
blah do |i|
  foo(i)
end

# bad
blah { |i|
  foo(i) }

# good
blah { |i|
  foo(i)
}

Style::BracesAroundHashParameters

Hashの最後のパラメータの括弧をチェック

Style::CaseIndentation

case式のインデントチェック

Style::ClassCheck

classの評価式をis_a?もしくわkind_of?に指定する

Style::ClosingParenthesisIndentation

メソッド内の閉じ括弧)のインデントをチェック

# good: when x is on its own line, indent this way
func(
  x,
  y
)

# good: when x follows opening parenthesis, align parentheses
a = b * (x +
         y
        )

# bad
def func(
  x,
  y
  )

Style::CommentIndentation

コメントのインデントチェック

Style::ConditionalAssignmentHelper

ifcase文の時の変数の扱いをチェック

# bad
if foo
  bar = 1
else
  bar = 2
end

case foo
when 'a'
  bar += 1
else
  bar += 2
end

if foo
  some_method
  bar = 1
else
  some_other_method
  bar = 2
end

# good
bar = if foo
        1
      else
        2
      end

bar += case foo
       when 'a'
         1
       else
         2
       end

bar << if foo
         some_method
         1
       else
         some_other_method
         2
       end

Style::Documentation

classmoduleのトップレベルのドキュメントをチェック

Style::DoubleNegation

二重否定!!をチェック


# bad
!!something

# good
!something.nil?

Style::EachWithObject

each_with_objectに置き換えれるかをチェック

# bad
[1, 2].inject({}) { |a, e| a[e] = e; a }

# good
[1, 2].each_with_object({}) { |e, a| a[e] = e }

Style::EmptyLineBetweenDefs

メソッド定義が空行で分離されているかチェック

Style::EmptyLines

2つ以上の連続した空行をチェック

Style::EmptyLinesAroundBlockBody

ブロック周りの空行をチェック

  • default : no_empty_lines
something do

  ...
end

Style::EmptyLinesAroundClassBody

class周りの空行をチェック

  • default : no_empty_lines
class Test

   def something
     ...
   end

end

Style::EmptyLinesAroundMethodBody

メソッド周りの空行をチェック

  • default : no_empty_lines
def something(arg)

  ...
end

Style::EmptyLinesAroundModuleBody

module周りの空行をチェック

  • default : no_empty_lines
module Test

   def something
     ...
   end

end

Style::ExtraSpacing

余分な空白をチェック

# good if AllowForAlignment is true
name      = "RuboCop"
# Some comment and an empty line

website  += "/bbatsov/rubocop" unless cond
puts        "rubocop"          if     debug

# bad for any configuration
set_app("RuboCop")
website  = "https://github.com/bbatsov/rubocop"

Style::FirstParameterIndentation

メソッド呼び出しの最初のパラメータをチェック

# bad
some_method(
first_param,
second_param)

# good
some_method(
  first_param,
second_param)

Style::FormatString

Stringのフォーマットメソッドを指定

  • default : format

SupportedStyles

  • format
  • sprintf
  • percent

Style::GuardClause

ガード句に置き換えることが可能な条件を確認します

# bad
def test
  if something
    work
  end
end

# good
def test
  return unless something
  work
end

# also good
def test
  work if something
end

# bad
if something
  raise 'exception'
else
  ok
end

# good
raise 'exception' if something
ok

Style::HashSyntax

Hashのシンタックスをチェックする

  • default : ruby19( { key: "value" } )

SupportedStyles

  • ruby19
  • ruby19_no_mixed_keys
  • hash_rockets

Style::IfUnlessModifier

if式が1行で収まるかチェック

Style::IndentationWidth

インデントが2スペースかチェック

class A
 def test
  puts 'hello'
 end
end

Style::ModuleFunction

module内のextend selfをチェック

module Test
  extend self

  ...

Style::MultilineBlockLayout

ブロック開始後に改行が入ってるかチェック

# bad
blah do |i| foo(i)
  bar(i)
end

# bad
blah do
  |i| foo(i)
  bar(i)
end

# good
blah do |i|
  foo(i)
  bar(i)
end

# bad
blah { |i| foo(i)
  bar(i)
}

# good
blah { |i|
  foo(i)
  bar(i)
}

Style::MutableConstant

定数が変更可能でないかチェック

# bad
CONST = [1, 2, 3]

# good
CONST = [1, 2, 3].freeze

Style::NumericLiterals

大きな数値にアンダースコアを入れるか

  • default : MinDigits: 5

Style::PercentLiteralDelimiters

%リテラル記法の括弧をチェック

PreferredDelimiters

'%':  ()
'%i': ()
'%q': ()
'%Q': ()
'%r': '{}'
'%s': ()
'%w': ()
'%W': ()
'%x': ()

Style::RaiseArgs

raise,fail時の引数指定をチェック

  • default : EnforcedStyle: exploded

SupportedStyles

  • compact # raise Exception.new(msg)
  • exploded # raise Exception, msg

Style::RedundantBegin

冗長なbeginブロックをチェック

def redundant
  begin
    ala
    bala
  rescue StandardError => e
    something
  end
end

def preferred
  ala
  bala
rescue StandardError => e
  something
end

Style::RedundantFreeze

不変オブジェクトのfreezeをチェック

# bad
CONST = 1.freeze

# good
CONST = 1

Style::RedundantParentheses

冗長な括弧をチェック

# bad
(x) if ((y.z).nil?)

# good
x if y.z.nil?

Style::RedundantSelf

冗長なselfをチェック

def bar :baz end

def foo(bar) self.bar # resolves name clash with argument end

def foo2 bar = 1 self.bar # resolves name clash with local variable end

writer attributeのローカル代入

attr_writer :bar

def foo self.bar= 1 # Make sure above attr writer is called end

Style::Semicolon

同じ行に配置された場合のセミコロンをチェック

Style::SpaceAfterComma

コンマの後のスペースをチェック

Style::SpaceAroundEqualsInParameterDefault

=間のスペースをチェック

Style::SpaceBeforeBlockBraces

左側のブロックフレーズのスペースをチェック

Style::SpaceBeforeComma

コンマの前のスペースをチェック

Style::SpaceBeforeFirstArg

メソッドの最初の引数はスペース無しで呼び出せる

Style::SpaceInsideBlockBraces

ブロック呼び出しに利用するブレース開始直後、ブレース終了直前、空ブレースの間に半角スペースを必要とするかどうかを
設定・チェックする。

Style::SpaceInsideHashLiteralBraces

ハッシュリテラルに利用するブレース開始直後、ブレース終了直前、空ブレースの間に半角スペースを必要とするかどうかを
設定・チェックする。

Style::SpaceInsideParens

丸括弧(のスペースをチェック

Style::StringLiterals

変数展開や文字列中にシングルクォートを含む場合など、特別な理由がなくダブルクォートを使っていないかチェックする。

Style::SymbolProc

symbol procが使えるかチェック

# bad
something.map { |s| s.upcase }

# good
something.map(&:upcase)

Style::TrailingBlankLines

ファイルの末尾の行に余分な空白があるかチェックをする。

Style::TrailingComma

ArrayやHashの末尾のカンマをチェックする

# always bad
a = [1, 2,]

# good if EnforcedStyleForMultiline is consistent_comma
a = [
  1, 2,
  3,
]

# good if EnforcedStyleForMultiline is comma or consistent_comma
a = [
  1,
  2,
]

# good if EnforcedStyleForMultiline is no_comma
a = [
  1,
  2
]

Style::TrailingWhitespace

末尾の空白をチェックする

Style::UnneededInterpolation

文字列が無駄に変数展開されてないかチェックする

# bad
"#{@var}"

# good
@var.to_s

# good if @var is already a String
@var

Style::UnneededPercentQ

%Q及び%q構文をチェックする。シングルクォートやダブルクォートで済むものをチェック。

Style::WordArray

文字列配列を %w / %W 記法で記述しているかどうかチェックする。

SupportedStyles

  • percent # percent style: %w(word1 word2)
  • brackets # bracket style: ['word1', 'word2']

Rubocop関連記事まとめ

下記に幾つか設定値等についてまとめられています

http://qiita.com/tbpgr/items/edbfecb6a6789dd54f47

Rubocop.yml

よく使ってる設定をGistに公開しました

159
149
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
159
149