LoginSignup
48
43

More than 1 year has passed since last update.

Rubocop がチェックしてくれるもの一覧表 (Style編)

Last updated at Posted at 2015-10-15

基本的に Rubocop - Rubydoc を元に書いてます。
一部、RubyStyleGuideからの引用や、自分で書いたサンプルもあります。

=> GitHub

  • 未完成のため、追記要望があれば編集リクエストをお送りください。

AccessModifierIndentation

private / protected / public は def と同じ列に書こう。

# bad
class SomeClass
private
  
  def private_method
    # ...
  end
end

# good
class SomeClass
  private
  
  def private_method
    # ...
  end
end

AccessorMethodName

セッタは attribute= というメソッド名にしよう。
ゲッタは attribute というメソッド名にしよう。

先頭に set_ / get_ は不要だ。

# bad
def set_attribute(value) ...

# good
def attribute=(value)

# bad
def get_attribute ...

# good
def attribute ...

(※単純なセッタ/ゲッタの場合は attr_accessor/attr_reader/attr_writer を使おう)

Alias

AlignArray

AlignHash

AlignParameters

AndOr

and は && に置き換えよう。
or は || に置き換えよう。

and / or は使う価値が無い。

RubyStyleGuide

###ArrayJoin

Array#join をする時に * を使わないようにしよう。謎めいた書き方だ。
明確に join を書こう。

# 悪い例
%w(one two three) * ', '
# => 'one, two, three'

# 良い例
%w(one two three).join(', ')
# => 'one, two, three'

(Ruby Style Guide より)

AsciiComments

AssignmentInCondition

if の中で代入するのはやめよう。( == の書き間違えに見える )

# bad
if x = 1 
end

AsciiIdentifiers

###Attr

attr は ruby のバージョンによって挙動が違う。
Ruby 1.8 以前では、引数によってゲッタ/セッタのどちらを定義するかが変わってしまう。分かりにくい。

かわりに attr_read / attr_writer / attr_accessor を使おう。

# 例
attr_accessor :getter_with_setter
attr_reader :getter1, :getter2, :getter3
attr_writer :setter1, :setter2, :setter3

RubyStyleGuideより

BeginBlock

BlockComments

ブロックコメントを使うのはやめよう。

エディタにもよるが、簡単にコメントだと見分けがつかない。
あとは、=begin =end の前に空白を置くことも出来ない。

# 悪い例
== begin
comment line
another comment line
== end

# 良い例
# comment line
# another comment line

RubyStyleGuide

BlockNesting

Blocks

BracesAroundHashParameters

CaseEquality

CaseIndentation

case 文で、when のインデントが不整列なら見つけてくれる。
(case / when / end はすべて同じ列に書くこと )

# bad
case
  when song.name == 'Misty'
    puts 'Not again!'
  when song.duration > 120
    puts 'Too long!'
  when Time.now.hour > 21
    puts "It's too late"
  else
    song.play
end

# good
case
when song.name == 'Misty'
  puts 'Not again!'
when song.duration > 120
  puts 'Too long!'
when Time.now.hour > 21
  puts "It's too late"
else
  song.play
end

CharacterLiteral

ClassAndModuleCamelCase

ClassAndModuleChildren

ClassLength

ClassMethods

ClassVars

CollectionMethods

ColonMethodCall

CommentAnnotation

アノテーションコメントは正しい形式で書こう。

# bad
#FIXME Comment

# good
# FIXME: Comment

ConstantName

CyclomaticComplexity

DefWithParentheses

DeprecatedHashMethods

Documentation

DotPosition

DoubleNegation

EmptyLineBetweenDefs

EmptyLines

EmptyLinesAroundAccessModifier

EmptyLinesAroundBody

###EmptyLiteral

空のリテラルを定義するとき。

Array.new のかわりに [] を使おう。
Hash.new のかわりに {} を使おう。
String.new のかわりに '' を使おう。

some_array = []
some_hash = {}
some_string = ''

Encoding

EndBlock

EndOfLine

コード内にCRの改行コード ( \r ) があれば見つけてくれる。

###EvenOdd

<<<<<<< HEAD
偶数の判定には even? を。
奇数の判定には odd? を使おう。

偶数の判定には even? を。
奇数の判定には odd? を使おう。

EDIT_REQUEST

# bad
if x % 2 == 0

# good
if x.even?

FileName

FinalNewline

FlipFlop

For

FormatString

GlobalVars

ユーザー定義のグローバル変数は使わないようにしよう。
(デフォルトのもの以外は使わない)

# bad
$ORIGINAL_PATH = '/path/to/user'
puts $ORIGINAL_PATH

# good
puts $LOAD_PATH

GuardClause

HashSyntax

新しいハッシュ記法でシンボルを書こう。

# bad
hash = { :kind => 'Apple' }

# good
hash = { kind: 'Apple' }

IfUnlessModifier

IfWithSemicolon

IndentArray

IndentHash

###IndentationConsistency

インデントには矛盾がないように。

def test
  puts 'hello'
-   puts 'world'
+  puts 'world'
end

IndentationWidth

インデントにはスペース二個を使うこと。

# bad
def test
 puts 'hello'
end

# good
def test
  puts 'hello'
end

Lambda

LambdaCall

LeadingCommentSpace

コメントの # の後にはスペースを置こう。
ただし、Rdoc用の記述では スペースを詰めて書いても良い。

MultilineIfThen

条件文を複数行で書くときに then は不要だ。

# bad
if cond then
end

# good
if cond
end

# good
if cond then a
elsif cond then b
end

SpaceBeforeBlockBraces

ブレースの前にはスペースを置こう。

- expect{ subject } 
+ expect { subject } 

MultilineTernaryOperator

三項演算子を複数行で書かないようにしよう。
その場合は if か unless を使おう。

# bad
true ?
yes :
no

# good
true ? yes : no

# good
if true
  yes
else
  no
end

###LineEndConcatenation

行末で文字連結をするときは \ を使おう。

# bad
some_str = 'ala' +
           'bala'

some_str = 'ala' <<
           'bala'

# good
some_str = 'ala' \
           'bala'

LineLength

MethodCallParentheses

MethodCalledOnDoEndBlock

MethodDefParentheses

メソッドを定義するとき。
メソッドが何のパラメータも受け取らない時は、カッコを省略しよう。

# bad
def some_method()
 # body omitted
end

# good
def some_method
 # body omitted
end

# bad
def some_method_with_parameters param1, param2
 # body omitted
end

# good
def some_method_with_parameters(param1, param2)
 # body omitted
end

MethodLength

MethodName

メソッド名は snake_case にしよう。

# bad
def ExampleMethod
end

# good
def example_method
end

設定によっては camelCase に揃えることも出来る。

ModuleFunction

MultilineBlockChain

MultilineIfThen

MultilineTernaryOperator

NegatedIf

NegatedWhile

NestedTernaryOperator

NilComparison

NonNilCheck

「nilでないこと」を冗長に判定していないか。


# bad
if x != nil
if !x.nil?

# good
if x

ただし最後の節として記述するならOK。

# good
def signed_in?
  !current_user.nil?
end

Not

NumericLiterals

OneLineConditional

OpMethod

ParameterLists

ParenthesesAroundCondition

条件文のカッコを省略できる場合はしよう。


# bad
if (a && b)
end

# good
if a && b
end

# good

if (a && b) || c
end

PercentLiteralDelimiters

PerlBackrefs

PredicateName

メソッド名の最初に has / have / is などの前置詞は不要だ。

# bad
def is_even?(value) ...

# good
def even?(value)

# bad
def has_value? ...

# good
def value? ...

Proc

RaiseArgs

RedundantBegin

例外処理がメソッド定義全体に対して行われる場合には begin と end を省略できる (参照)

省略しよう。

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

def preferred
  ala
  bala
rescue StandardError => e
  something
end

RedundantException (中途半端な例外)

RuntimeError を起こす場合は、クラス名は省略できる。
( raise / fail のデフォルトが RuntimeError なので )

# bad
raise RuntimeError, 'message'

# good - signals a RuntimeError by default
raise 'message'

RedundantException

RedundantReturn

冗長な return はやめよう。

# maybe bad
def test
  return something
end

# maybe good
def test
  something
end

RescueEnsureAlignment

begin/rescue/end はすべて同じ列に書こう。

# bad
begin
  something
  rescue
  puts 'error'
end

# good
begin
  something
rescue
  puts 'error'
end

RedundantSelf

RegexpLiteral

詳しくは RuboCop | Style/RegexpLiteral - Qiita を参照。

設定によって、判定の動作が変わる。
オプションは slashes (デフォルト) / percent_r / mixed の三種類。

.rubocop.yml
#例:

Style/RegexpLiteral:
  EnforcedStyle: percent_r
# EnforcedStyle の設定が slashes / mixed の場合は良い。 percent_r の場合は悪い。
snake_case = /^[\dA-Z_]+$/

# EnforcedStyle の設定が percent_r の場合は良い。 slashes / mixed の場合は悪い。
snake_case = %r{^[\dA-Z_]+$}

# EnforcedStyle の設定が slashes の場合は良い。 percent_r / mixed の場合は悪い。
regex = /
  foo
  (bar)
  (baz)
/x

# EnforcedStyle の設定が percent_r / mixed の場合は良い。 slashes の場合は悪い。
regex = %r{
  foo
  (bar)
  (baz)
}x

# スラッシュ記法の中でスラッシュを使わないこと。
# AllowInnerSlashes の設定を true にしていれば警告しない。
x =~ /home\//

RescueModifier

SelfAssignment

変数が自分自身を扱う場合は、簡潔な書き方をしよう。

# bad
x = x + 1

# good
x += 1

Semicolon

SignalException

SingleLineBlockParams

SingleLineMethods

メソッドを1行で定義しないこと。

# bad
def method; nil; end

# good
def method
  nil
end

ただしオプションで、メソッドのボディがない場合に限り許容させることも出来る。

SingleSpaceBeforeFirstArg

SpaceAfterColon

いくつかの場合、セミコロンの後にスペースを置こう。

# bad
x = 1;y = 2

# good
x = 1; y = 2

SpaceAroundBlockParameters

ブロックパラメータの外側には空白を置こう。
逆に内側には置かないようにしよう。

# bad
hash.map! {|k, v|v }

# bad
hash.map { | k, v | v }

# good
hash.map { |k, v| v }

SpaceAfterComma

(いくつかの種類の)カンマの後にはスペースを置こう。

#bad
['Apple','Banana','Strawberry']

#good
['Apple', 'Banana', 'Strawberry']

SpaceAfterControlKeyword

1行で書く場合。
if/unless などの後にはスペースを置こう。

# bad
if(a && b) || c then result end

# good_
if (a && b) || c then result end

SpaceAfterMethodName

メソッドを定義するとき。
メソッド名とカッコの間は、スペースを置かずに詰めよう。

# bad
def func (x)
end

# good
def func(x)
end

SpaceAfterNot ( ! の後の空白 )

! の後にスペースを置かないようにしよう。

# bad
! something

# good
!something

SpaceAfterSemicolon

1行に複数式を書く場合。
セミコロンの後にはスペースを置こう。

# bad
x = 1;y = 2;

# good
x = 1; y = 2;

SpaceAroundEqualsInParameterDefault

引数の初期値を決めるとき。イコールの周りには空白を置こう。

# bad
def example(value='')
end

# good
def example(value = '')
end

SpaceAroundOperators ( 演算子の周りの空白 )

演算子の周りには空白を1個置こう。

# bad
x=1+1

# bad
x  =  1  +  1

# good
x = 1 + 1

ただし ** (乗の計算) ではスペースを置くべきではない。

# bad
x = 2 ** 3

# good
x = 2**3

SpaceBeforeBlockBraces

ブロックの波括弧の前にはスペースを置こう。

# bad
(1..10).each{ |i| i }

# good
(1..10).each { |i| i }

SpaceBeforeComment

行末コメントの前にはスペースを置こう。

# bad
method# Comment

# good
method # Comment

SpaceBeforeModifierKeyword

後方の if/unless などの前にはスペースを置こう。

# bad
result if(a && b) || c

# good
result if (a && b) || c

SpaceInsideBlockBraces

ブロックの波括弧の内側にはスペースを置こう。

# bad
(1..10).each {|i| i}

# good
(1..10).each { |i| i }

SpaceInsideBrackets

SpaceInsideHashLiteralBraces

ハッシュ記法で、波括弧の内側にはスペースを置こう。

# bad
furuits = {apple: 10, banana: 20}

# good
furuits = { apple: 10, banana: 20 }

SpaceInsideParens

カッコの内側にはスペースを置かないようにしよう。

# bad
some( arg ).other
[ 1, 2, 3 ].size

# good
some(arg).other
[1, 2, 3].size

SpaceInsideRangeLiteral

範囲リテラルの内側にスペースは不要だ。

# bad
1 .. 3

# good
1..3

# bad
'a' .. 'z'

# good
'a'..'z'

SpecialGlobalVars

スーパーグローバル変数を Perl スタイルで書かないようにしよう。
かわりに、意味が明確な方のスタイルで書こう。

対照表:

$: => $LOAD_PATH
$" => $LOADED_FEATURES
$0 => $PROGRAM_NAME
$! => $ERROR_INFO
$@ => $ERROR_POSITION
$; => $FIELD_SEPARATOR / $FS
$, => $OUTPUT_FIELD_SEPARATOR / $OFS
$/ => $INPUT_RECORD_SEPARATOR / $RS
$\\ => $OUTPUT_RECORD_SEPARATOR / $ORS
$. => $INPUT_LINE_NUMBER / $NR
$_ => $LAST_READ_LINE
$> => $DEFAULT_OUTPUT
$< => $DEFAULT_INPUT
$$ => $PROCESS_ID / $PID
$? => $CHILD_STATUS
$~ => $LAST_MATCH_INFO
$= => $IGNORECASE
$* => $ARGV => / => ARGV
$& => $MATCH
$` => $PREMATCH
$\' => $POSTMATCH
$+ => $LAST_PAREN_MATCH

StringLiterals

SymbolArray

SymbolLiteral

文字定義みたいなシンボルは書かないようにしよう。

# bad
:symbol"

# good
:symbol

Tab

タブ ( \t ) を使わないようにしよう。

(*注…プログラミングの世界では、タブ揃えより、空白スペース揃えのほうが主流だ)

SymbolProc

proc をシンボル記法に置き換えられる場合は、そうしよう。

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

# good
something.map(&:upcase)

TrailingBlankLines

ファイル末には空行を入れないようにしよう。

TrailingComma

TrailingWhitespace

行末の空白を見つけてくれる。

TrailingUnderscoreVariable

変数はアンダースコアで終わらせないようにしよう。

# maybe bad
x_ = 1

TrivialAccessors

ありふれたセッタ/ゲッタメソッドは、 attr_xxx に置き換えよう。

# bad
class Foo
  def example=(value)
    @example = value
  end

  def example
    @example
  end
end

# good
class Foo
  attr_accessor :example
end

UnlessElse

VariableInterpolation

VariableName

変数は snake_case で書こう。

# bad
someVar = 5

# good
some_var = 5

設定次第では camelCase に統一させることも出来る

WhenThen

when then の表現でセミコロンを使わないこと。then を使うこと。

# bad
when x; apple

# good
when x then apple

WhileUntilDo

複数行の while/until に do が使われている部分を見つけてくれる。

# bad
while x > 5 do
  # body omitted
end

until x > 5 do
  # body omitted
end

# good
while x > 5
  # body omitted
end

until x > 5
  # body omitted
end

WhileUntilModifier

WordArray

Metrics

ParameterLists

メソッド定義では。引数の種類を増やし過ぎないようにしよう。

# bad 
class Example
  def some_method(argument1, argument2, argument3, argument4, argument5, argument6)
  end
end

設定によって警告の個数は変更できる。

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

48
43
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
48
43