0
0

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 1 year has passed since last update.

List of things that Rubocop will check (Style)

Last updated at Posted at 2019-04-16

Basically, it is written based on Rubocop-Rubydoc . There are also some quotes from RubyStyleGuide, and some examples that you wrote yourself.

=> GitHub

  • Please send an edit request if there is a request for addition because it is not completed.

AccessModifierIndentation

Write private / protected / public in the same column as def.

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

AccessorMethodName

Setter should be named attribute = method. Let's get the getter method name attribute.

You do not need set_ / get_ at the beginning

 # bad def set_attribute(value) ... # good def attribute=(value) # bad def get_attribute ... # good def attribute ... 

(※ For simple setter / getter, use attr accessor / attr reader / attr_writer)

Alias

AlignArray

AlignHash

AlignParameters

AndOr

Let's replace and with &&. Let's replace or with ||.

and / or is not worth using.

RubyStyleGuide

ArrayJoin

Do not use * when doing Array # join. It is a mysterious writing. Write the join clearly.

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

(From Ruby Style Guide)

AsciiComments

AssignmentInCondition

Let's stop assigning in if. (It looks like a mistake in writing = =)

 # bad if x = 1 end 

AsciiIdentifiers

Attr

attr behaves differently depending on the ruby version. In Ruby 1.8 and earlier, the argument changes which of getter / setter is defined. Confusing.

Use attr read / attr writer / attr_accessor instead.

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

From RubyStyleGuide

BeginBlock

BlockComments

Stop using block comments.

It depends on the editor, but it is not easy to distinguish between comments. After that, you can not put a space before = begin = end.

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

RubyStyleGuide

BlockNesting

Blocks

BracesAroundHashParameters

CaseEquality

CaseIndentation

In case statements, if the indent of when is misaligned, it will be found. (case / when / end should all be written in the same column)

 # 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

Write annotations in the correct format.

 # bad #FIXME Comment # good # FIXME: Comment 

ConstantName

Cyclomatic Complexity

DefWithParentheses

DeprecatedHashMethods

Documentation

DotPosition

DoubleNegation

EmptyLineBetweenDefs

EmptyLines

EmptyLinesAroundAccessModifier

EmptyLinesAroundBody

EmptyLiteral

When defining an empty literal.

Use [] instead of Array.new. Use {} instead of Hash.new. Use '' instead of String.new.

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

Encoding

EndBlock

EndOfLine

It will find any CR carriage returns (\ r) in the code.

EvenOdd

<<<<<<< HEAD even? For even judgment.

Use odd? For odd judgment.

The judgment of the even-numbered even? A. Use odd? judgment.

EDIT_REQUEST

 # bad if x % 2 == 0 # good if x.even? 

FileName

FinalNewline

FlipFlop

For

FormatString

GlobalVars

Avoid using user-defined global variables. (Do not use anything other than the default

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

GuardClause

HashSyntax

Write a symbol in the new hash notation.

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

IfUnlessModifier

IfWithSemicolon

IndentArray

IndentHash

IndentationConsistency

There is no contradiction in indent.

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

IndentationWidth

Use two spaces for indenting.

 # bad def test puts 'hello' end # good def test puts 'hello' end 

Lambda

LambdaCall

LeadingCommentSpace

Place a space after the comment # . However, in the description for Rdoc, you may write it with spaces.

MultilineIfThen

You do not need then when you write conditional statements on multiple lines.

 # bad if cond then end # good if cond end # good if cond then a elsif cond then b end 

SpaceBeforeBlockBraces

Place a space in front of the braces.

 - expect{ subject } + expect { subject } 

MultilineTernaryOperator

Do not write ternary operators on multiple lines. In that case, use if or unless.

 # bad true ? yes : no # good true ? yes : no # good if true yes else no end 

LineEndConcatenation

Use \ to concatenate at the end of a line.

 # bad some_str = 'ala' + 'bala' some_str = 'ala' << 'bala' # good some_str = 'ala' \ 'bala' 

LineLength

MethodCallParentheses

MethodCalledOnDoEndBlock

MethodDef Parentheses

When defining a method. If the method does not receive any parameters, omit the parentheses.

 # 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

Method name should be snake_case.

 # bad def ExampleMethod end # good def example_method end 

Depending on the setting, it can be aligned with camelCase.

ModuleFunction

MultilineBlockChain

MultilineIfThen

MultilineTernaryOperator

NegatedIf

NegatedWhile

NestedTernaryOperator

NilComparison

NonNilCheck

Have you judged "non-nil" redundantly?

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

However, if it describes as the last clause, it is OK.

 # good def signed_in? !current_user.nil? end 

Not

NumericLiterals

OneLineConditional

OpMethod

ParameterLists

ParenthesesAroundCondition

If you can omit the parentheses in the conditional statement, try it.

 # bad if (a && b) end # good if a && b end # good if (a && b) || c end 

PercentLiteralDelimiters

PerlBackrefs

PredicateName

Prefixes such as has / have / is are not required at the beginning of method names.

 # bad def is_even?(value) ... # good def even?(value) # bad def has_value? ... # good def value? ... 

Proc

Raiseargs

RedundantBegin

If exception handling is performed on the entire method definition, begin and end can be omitted ( reference )

I will omit it.

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

RedundantException (half-finished exception)

The class name can be omitted if a RuntimeError occurs. (Because the default of raise / fail is RuntimeError)

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

RedundantException

RedundantReturn

Let's stop the redundant return.

 # maybe bad def test return something end # maybe good def test something end 

RescueEnsureAlignment

Write begin / rescue / end all in the same column.

 # bad begin something rescue puts 'error' end # good begin something rescue puts 'error' end 

RedundantSelf

RegexpLiteral

See RuboCop | Style / RegexpLiteral-Qiita for details.

The setting operation changes the judgment operation. The options are slashes (default) / percent_r / mixed.

 #例: 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

If the variable deals with itself, write it concisely.

 # bad x = x + 1 # good x += 1 

Semicolon

SignalException

SingleLineBlockParams

SingleLineMethods

Do not define a method on one line.

 # bad def method; nil; end # good def method nil end 

However, it can optionally be allowed only if there is no method body.

SingleSpaceBeforeFirstArg

SpaceAfterColon

In some cases, put a space after the semicolon.

 # bad x = 1;y = 2 # good x = 1; y = 2 

SpaceAroundBlockParameters

Leave a space outside the block parameter. Conversely, try not to put it inside.

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

SpaceAfterComma

Place a space after the commas (of several types).

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

SpaceAfterControlKeyword

When writing in one line. Place a space after if / unless etc.

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

SpaceAfterMethodName

When defining a method. Do not leave a space between method names and parentheses.

 # bad def func (x) end # good def func(x) end 

SpaceAfterNot (Space after!)

Do not leave a space after!

 # bad ! something # good !something 

SpaceAfterSemicolon

When writing multiple expressions on one line. Place a space after the semicolon.

 # bad x = 1;y = 2; # good x = 1; y = 2; 

SpaceAroundEqualsInParameterDefault

When deciding the initial value of the argument. Leave a space around the equal.

 # bad def example(value='') end # good def example(value = '') end 

SpaceAroundOperators (space around operators)

Put a space around the operator.

 # bad x=1+1 # bad x = 1 + 1 # good x = 1 + 1 

However, ** (squares) should not have space.

 # bad x = 2 **3 # good x = 2** 3 

SpaceBeforeBlockBraces

Place a space before the block braces.

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

SpaceBeforeComment

Place a space before the end of line comment.

 # bad method# Comment # good method # Comment 

SpaceBeforeModifierKeyword

Put a space in front of if / unless etc. behind.

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

SpaceInsideBlockBraces

Place a space inside the block braces.

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

SpaceInside Brackets

SpaceInsideHashLiteralBraces

In hash notation, put a space inside the braces.

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

SpaceInsideParens

Don't put a space inside the brackets.

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

SpaceInsideRangeLiteral

Spaces are not required inside range literals.

 # bad 1 .. 3 # good 1..3 # bad 'a' .. 'z' # good 'a'..'z' 

SpecialGlobalVars

Do not write superglobal variables in Perl style. Instead, write in the style of the one whose meaning is clear.

Control chart:

 $: => $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

Do not write symbols that are like letter definitions.

 # bad :symbol" # good :symbol 

Tab

Try not to use tabs (\ t).

(* Note ... In the programming world, blank space alignment is more mainstream than tab alignment)

SymbolProc

If you can replace proc with symbol notation, do so.

 # bad something.map { |s| s.upcase } # good something.map(&:upcase) 

TrailingBlankLines

Don't put an empty line at the end of the file.

Trailing Comma

TrailingWhitespace

It finds the space at the end of the line.

TrailingUnderscoreVariable

Do not end variables with underscores.

 # maybe bad x_ = 1 

TrivialAccessors

attr_xxx common setter / getter methods with 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

Write variables in snake_case.

 # bad someVar = 5 # good some_var = 5 

You can unify it into camelCase depending on the setting.

WhenThen

Do not use semicolons in when then expressions. use then.

 # bad when x; apple # good when x then apple 

WhileUntilDo

It finds out where do is used in multiple lines of while / until.

 # 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

In the method definition. Try not to add too many types of arguments.

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

The number of warnings can be changed by setting.

Original by

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

About

About this translattion

チャットメンバー募集

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

Twitter

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?