From bcb1522ecd9da41461b9e82ae89241bbe5d70997 Mon Sep 17 00:00:00 2001 From: Simon Huber Date: Sun, 16 Oct 2016 01:25:36 +0200 Subject: [PATCH] [#3246] add list of all cops with documentation --- CHANGELOG.md | 3 + lib/rubocop/cop/lint/shadowed_exception.rb | 3 +- lib/rubocop/cop/style/empty_else.rb | 16 +- .../space_inside_array_percent_literal.rb | 9 +- ...space_inside_percent_literal_delimiters.rb | 13 +- manual/cops.md | 317 ++ manual/cops_lint.md | 1180 ++++ manual/cops_metrics.md | 213 + manual/cops_performance.md | 660 +++ manual/cops_rails.md | 658 +++ manual/cops_security.md | 37 + manual/cops_style.md | 4792 +++++++++++++++++ ...space_inside_array_percent_literal_spec.rb | 18 +- ..._inside_percent_literal_delimiters_spec.rb | 24 +- tasks/cops_documentation.rake | 113 + tasks/new_cop.rake | 1 + 16 files changed, 8018 insertions(+), 39 deletions(-) create mode 100644 manual/cops_lint.md create mode 100644 manual/cops_metrics.md create mode 100644 manual/cops_performance.md create mode 100644 manual/cops_rails.md create mode 100644 manual/cops_security.md create mode 100644 manual/cops_style.md create mode 100644 tasks/cops_documentation.rake diff --git a/CHANGELOG.md b/CHANGELOG.md index 326709e3ee9d..39ff61b66389 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,8 @@ # Change log ## master (unreleased) +* [#3246](https://github.com/bbatsov/rubocop/issues/3246): Add list of all cops to Documentation. ([@sihu][]) + ### New features @@ -2441,3 +2443,4 @@ [@legendetm]: https://github.com/legendetm [@bronson]: https://github.com/bronson [@albus522]: https://github.com/albus522 +[@sihu]: https://github.com/sihu diff --git a/lib/rubocop/cop/lint/shadowed_exception.rb b/lib/rubocop/cop/lint/shadowed_exception.rb index e961a2a1631f..701cbeb77f05 100644 --- a/lib/rubocop/cop/lint/shadowed_exception.rb +++ b/lib/rubocop/cop/lint/shadowed_exception.rb @@ -7,8 +7,7 @@ module Lint # less specific exception being rescued before a more specific # exception is rescued. # - # @example - # + # @example # # bad # begin # something diff --git a/lib/rubocop/cop/style/empty_else.rb b/lib/rubocop/cop/style/empty_else.rb index 7267df8aed9a..a7d785a5445e 100644 --- a/lib/rubocop/cop/style/empty_else.rb +++ b/lib/rubocop/cop/style/empty_else.rb @@ -10,6 +10,7 @@ module Style # # @example # # good for all styles + # # if condition # statement # else @@ -21,8 +22,9 @@ module Style # statement # end # - # empty - warn only on empty else - # @example + # @example + # # empty - warn only on empty else + # # # bad # if condition # statement @@ -36,8 +38,9 @@ module Style # nil # end # - # nil - warn on else with nil in it - # @example + # @example + # # nil - warn on else with nil in it + # # # bad # if condition # statement @@ -51,8 +54,9 @@ module Style # else # end # - # both - warn on empty else and else with nil in it - # @example + # @example + # # both - warn on empty else and else with nil in it + # # # bad # if condition # statement diff --git a/lib/rubocop/cop/style/space_inside_array_percent_literal.rb b/lib/rubocop/cop/style/space_inside_array_percent_literal.rb index d2dc3c985359..bdb9b286894c 100644 --- a/lib/rubocop/cop/style/space_inside_array_percent_literal.rb +++ b/lib/rubocop/cop/style/space_inside_array_percent_literal.rb @@ -6,11 +6,12 @@ module Style # Checks for unnecessary additional spaces inside array percent literals # (i.e. %i/%w). # - # @good - # %i(foo bar baz) + # @example + # @good + # %i(foo bar baz) # - # @bad - # %w(foo bar baz) + # @bad + # %w(foo bar baz) class SpaceInsideArrayPercentLiteral < Cop include MatchRange include PercentLiteral diff --git a/lib/rubocop/cop/style/space_inside_percent_literal_delimiters.rb b/lib/rubocop/cop/style/space_inside_percent_literal_delimiters.rb index be897596bccf..7f316d8ea596 100644 --- a/lib/rubocop/cop/style/space_inside_percent_literal_delimiters.rb +++ b/lib/rubocop/cop/style/space_inside_percent_literal_delimiters.rb @@ -6,14 +6,15 @@ module Style # Checks for unnecessary additional spaces inside the delimiters of # %i/%w/%x literals. # - # @good - # %i(foo bar baz) + # @example + # @good + # %i(foo bar baz) # - # @bad - # %w( foo bar baz ) + # @bad + # %w( foo bar baz ) # - # @bad - # %x( ls -l ) + # @bad + # %x( ls -l ) class SpaceInsidePercentLiteralDelimiters < Cop include MatchRange include PercentLiteral diff --git a/manual/cops.md b/manual/cops.md index 3e5198122662..2c15e60d8bcc 100644 --- a/manual/cops.md +++ b/manual/cops.md @@ -57,3 +57,320 @@ or add the following directive to your `.rubocop.yml`: Rails: Enabled: true ``` + +### Available cops + +In the following section you find all available cops: + +#### Type [Lint](cops_lint.md) + +* [Lint/AmbiguousOperator](cops_lint.md/#lintambiguousoperator) +* [Lint/AmbiguousRegexpLiteral](cops_lint.md/#lintambiguousregexpliteral) +* [Lint/AssignmentInCondition](cops_lint.md/#lintassignmentincondition) +* [Lint/BlockAlignment](cops_lint.md/#lintblockalignment) +* [Lint/CircularArgumentReference](cops_lint.md/#lintcircularargumentreference) +* [Lint/ConditionPosition](cops_lint.md/#lintconditionposition) +* [Lint/Debugger](cops_lint.md/#lintdebugger) +* [Lint/DefEndAlignment](cops_lint.md/#lintdefendalignment) +* [Lint/DeprecatedClassMethods](cops_lint.md/#lintdeprecatedclassmethods) +* [Lint/DuplicateMethods](cops_lint.md/#lintduplicatemethods) +* [Lint/DuplicatedKey](cops_lint.md/#lintduplicatedkey) +* [Lint/EachWithObjectArgument](cops_lint.md/#linteachwithobjectargument) +* [Lint/ElseLayout](cops_lint.md/#lintelselayout) +* [Lint/EmptyEnsure](cops_lint.md/#lintemptyensure) +* [Lint/EmptyInterpolation](cops_lint.md/#lintemptyinterpolation) +* [Lint/EndAlignment](cops_lint.md/#lintendalignment) +* [Lint/EndInMethod](cops_lint.md/#lintendinmethod) +* [Lint/EnsureReturn](cops_lint.md/#lintensurereturn) +* [Lint/Eval](cops_lint.md/#linteval) +* [Lint/FloatOutOfRange](cops_lint.md/#lintfloatoutofrange) +* [Lint/FormatParameterMismatch](cops_lint.md/#lintformatparametermismatch) +* [Lint/HandleExceptions](cops_lint.md/#linthandleexceptions) +* [Lint/ImplicitStringConcatenation](cops_lint.md/#lintimplicitstringconcatenation) +* [Lint/IneffectiveAccessModifier](cops_lint.md/#lintineffectiveaccessmodifier) +* [Lint/InheritException](cops_lint.md/#lintinheritexception) +* [Lint/InvalidCharacterLiteral](cops_lint.md/#lintinvalidcharacterliteral) +* [Lint/LiteralInCondition](cops_lint.md/#lintliteralincondition) +* [Lint/LiteralInInterpolation](cops_lint.md/#lintliteralininterpolation) +* [Lint/Loop](cops_lint.md/#lintloop) +* [Lint/NestedMethodDefinition](cops_lint.md/#lintnestedmethoddefinition) +* [Lint/NextWithoutAccumulator](cops_lint.md/#lintnextwithoutaccumulator) +* [Lint/NonLocalExitFromIterator](cops_lint.md/#lintnonlocalexitfromiterator) +* [Lint/ParenthesesAsGroupedExpression](cops_lint.md/#lintparenthesesasgroupedexpression) +* [Lint/PercentStringArray](cops_lint.md/#lintpercentstringarray) +* [Lint/PercentSymbolArray](cops_lint.md/#lintpercentsymbolarray) +* [Lint/RandOne](cops_lint.md/#lintrandone) +* [Lint/RequireParentheses](cops_lint.md/#lintrequireparentheses) +* [Lint/RescueException](cops_lint.md/#lintrescueexception) +* [Lint/ShadowedException](cops_lint.md/#lintshadowedexception) +* [Lint/ShadowingOuterLocalVariable](cops_lint.md/#lintshadowingouterlocalvariable) +* [Lint/StringConversionInInterpolation](cops_lint.md/#lintstringconversionininterpolation) +* [Lint/UnderscorePrefixedVariableName](cops_lint.md/#lintunderscoreprefixedvariablename) +* [Lint/UnneededDisable](cops_lint.md/#lintunneededdisable) +* [Lint/UnreachableCode](cops_lint.md/#lintunreachablecode) +* [Lint/UnusedBlockArgument](cops_lint.md/#lintunusedblockargument) +* [Lint/UnusedMethodArgument](cops_lint.md/#lintunusedmethodargument) +* [Lint/UselessAccessModifier](cops_lint.md/#lintuselessaccessmodifier) +* [Lint/UselessArraySplat](cops_lint.md/#lintuselessarraysplat) +* [Lint/UselessAssignment](cops_lint.md/#lintuselessassignment) +* [Lint/UselessComparison](cops_lint.md/#lintuselesscomparison) +* [Lint/UselessElseWithoutRescue](cops_lint.md/#lintuselesselsewithoutrescue) +* [Lint/UselessSetterCall](cops_lint.md/#lintuselesssettercall) +* [Lint/Void](cops_lint.md/#lintvoid) + +#### Type [Metrics](cops_metrics.md) + +* [Metrics/AbcSize](#metricsabcsize) +* [Metrics/BlockNesting](#metricsblocknesting) +* [Metrics/ClassLength](#metricsclasslength) +* [Metrics/CyclomaticComplexity](#metricscyclomaticcomplexity) +* [Metrics/LineLength](#metricslinelength) +* [Metrics/MethodLength](#metricsmethodlength) +* [Metrics/ModuleLength](#metricsmodulelength) +* [Metrics/ParameterLists](#metricsparameterlists) +* [Metrics/PerceivedComplexity](#metricsperceivedcomplexity) + +#### Type [Performance](cops_performance.md) + +* [Performance/CaseWhenSplat](cops_performance.md/#performancecasewhensplat) +* [Performance/Casecmp](cops_performance.md/#performancecasecmp) +* [Performance/Count](cops_performance.md/#performancecount) +* [Performance/Detect](cops_performance.md/#performancedetect) +* [Performance/DoubleStartEndWith](cops_performance.md/#performancedoublestartendwith) +* [Performance/EndWith](cops_performance.md/#performanceendwith) +* [Performance/FixedSize](cops_performance.md/#performancefixedsize) +* [Performance/FlatMap](cops_performance.md/#performanceflatmap) +* [Performance/HashEachMethods](cops_performance.md/#performancehasheachmethods) +* [Performance/LstripRstrip](cops_performance.md/#performancelstriprstrip) +* [Performance/PushSplat](cops_performance.md/#performancepushsplat) +* [Performance/RangeInclude](cops_performance.md/#performancerangeinclude) +* [Performance/RedundantBlockCall](cops_performance.md/#performanceredundantblockcall) +* [Performance/RedundantMatch](cops_performance.md/#performanceredundantmatch) +* [Performance/RedundantMerge](cops_performance.md/#performanceredundantmerge) +* [Performance/RedundantSortBy](cops_performance.md/#performanceredundantsortby) +* [Performance/ReverseEach](cops_performance.md/#performancereverseeach) +* [Performance/Sample](cops_performance.md/#performancesample) +* [Performance/Size](cops_performance.md/#performancesize) +* [Performance/StartWith](cops_performance.md/#performancestartwith) +* [Performance/StringReplacement](cops_performance.md/#performancestringreplacement) +* [Performance/TimesMap](cops_performance.md/#performancetimesmap) + +#### Type [Rails](cops_rails.md) + +* [Rails/ActionFilter](cops_rails.md/#railsactionfilter) +* [Rails/Date](cops_rails.md/#railsdate) +* [Rails/Delegate](cops_rails.md/#railsdelegate) +* [Rails/Exit](cops_rails.md/#railsexit) +* [Rails/FindBy](cops_rails.md/#railsfindby) +* [Rails/FindEach](cops_rails.md/#railsfindeach) +* [Rails/HasAndBelongsToMany](cops_rails.md/#railshasandbelongstomany) +* [Rails/Output](cops_rails.md/#railsoutput) +* [Rails/OutputSafety](cops_rails.md/#railsoutputsafety) +* [Rails/PluralizationGrammar](cops_rails.md/#railspluralizationgrammar) +* [Rails/ReadWriteAttribute](cops_rails.md/#railsreadwriteattribute) +* [Rails/RequestReferer](cops_rails.md/#railsrequestreferer) +* [Rails/SaveBang](cops_rails.md/#railssavebang) +* [Rails/ScopeArgs](cops_rails.md/#railsscopeargs) +* [Rails/TimeZone](cops_rails.md/#railstimezone) +* [Rails/UniqBeforePluck](cops_rails.md/#railsuniqbeforepluck) +* [Rails/Validation](cops_rails.md/#railsvalidation) + +#### Type [Style](cops_style.md) + +* [Style/AccessModifierIndentation](cops_style.md/#styleaccessmodifierindentation) +* [Style/AccessorMethodName](cops_style.md/#styleaccessormethodname) +* [Style/Alias](cops_style.md/#stylealias) +* [Style/AlignArray](cops_style.md/#stylealignarray) +* [Style/AlignHash](cops_style.md/#stylealignhash) +* [Style/AlignParameters](cops_style.md/#stylealignparameters) +* [Style/AndOr](cops_style.md/#styleandor) +* [Style/ArrayJoin](cops_style.md/#stylearrayjoin) +* [Style/AsciiComments](cops_style.md/#styleasciicomments) +* [Style/AsciiIdentifiers](cops_style.md/#styleasciiidentifiers) +* [Style/Attr](cops_style.md/#styleattr) +* [Style/AutoResourceCleanup](cops_style.md/#styleautoresourcecleanup) +* [Style/BarePercentLiterals](cops_style.md/#stylebarepercentliterals) +* [Style/BeginBlock](cops_style.md/#stylebeginblock) +* [Style/BlockComments](cops_style.md/#styleblockcomments) +* [Style/BlockDelimiters](cops_style.md/#styleblockdelimiters) +* [Style/BlockEndNewline](cops_style.md/#styleblockendnewline) +* [Style/BracesAroundHashParameters](cops_style.md/#stylebracesaroundhashparameters) +* [Style/CaseEquality](cops_style.md/#stylecaseequality) +* [Style/CaseIndentation](cops_style.md/#stylecaseindentation) +* [Style/CharacterLiteral](cops_style.md/#stylecharacterliteral) +* [Style/ClassAndModuleCamelCase](cops_style.md/#styleclassandmodulecamelcase) +* [Style/ClassAndModuleChildren](cops_style.md/#styleclassandmodulechildren) +* [Style/ClassCheck](cops_style.md/#styleclasscheck) +* [Style/ClassMethods](cops_style.md/#styleclassmethods) +* [Style/ClassVars](cops_style.md/#styleclassvars) +* [Style/ClosingParenthesisIndentation](cops_style.md/#styleclosingparenthesisindentation) +* [Style/CollectionMethods](cops_style.md/#stylecollectionmethods) +* [Style/ColonMethodCall](cops_style.md/#stylecolonmethodcall) +* [Style/CommandLiteral](cops_style.md/#stylecommandliteral) +* [Style/CommentAnnotation](cops_style.md/#stylecommentannotation) +* [Style/CommentIndentation](cops_style.md/#stylecommentindentation) +* [Style/ConditionalAssignment](cops_style.md/#styleconditionalassignment) +* [Style/ConstantName](cops_style.md/#styleconstantname) +* [Style/Copyright](cops_style.md/#stylecopyright) +* [Style/DefWithParentheses](cops_style.md/#styledefwithparentheses) +* [Style/Documentation](cops_style.md/#styledocumentation) +* [Style/DotPosition](cops_style.md/#styledotposition) +* [Style/DoubleNegation](cops_style.md/#styledoublenegation) +* [Style/EachForSimpleLoop](cops_style.md/#styleeachforsimpleloop) +* [Style/EachWithObject](cops_style.md/#styleeachwithobject) +* [Style/ElseAlignment](cops_style.md/#styleelsealignment) +* [Style/EmptyCaseCondition](cops_style.md/#styleemptycasecondition) +* [Style/EmptyElse](cops_style.md/#styleemptyelse) +* [Style/EmptyLineBetweenDefs](cops_style.md/#styleemptylinebetweendefs) +* [Style/EmptyLines](cops_style.md/#styleemptylines) +* [Style/EmptyLinesAroundAccessModifier](cops_style.md/#styleemptylinesaroundaccessmodifier) +* [Style/EmptyLinesAroundBlockBody](cops_style.md/#styleemptylinesaroundblockbody) +* [Style/EmptyLinesAroundClassBody](cops_style.md/#styleemptylinesaroundclassbody) +* [Style/EmptyLinesAroundMethodBody](cops_style.md/#styleemptylinesaroundmethodbody) +* [Style/EmptyLinesAroundModuleBody](cops_style.md/#styleemptylinesaroundmodulebody) +* [Style/EmptyLiteral](cops_style.md/#styleemptyliteral) +* [Style/Encoding](cops_style.md/#styleencoding) +* [Style/EndBlock](cops_style.md/#styleendblock) +* [Style/EndOfLine](cops_style.md/#styleendofline) +* [Style/EvenOdd](cops_style.md/#styleevenodd) +* [Style/ExtraSpacing](cops_style.md/#styleextraspacing) +* [Style/FileName](cops_style.md/#stylefilename) +* [Style/FirstArrayElementLineBreak](cops_style.md/#stylefirstarrayelementlinebreak) +* [Style/FirstHashElementLineBreak](cops_style.md/#stylefirsthashelementlinebreak) +* [Style/FirstMethodArgumentLineBreak](cops_style.md/#stylefirstmethodargumentlinebreak) +* [Style/FirstMethodParameterLineBreak](cops_style.md/#stylefirstmethodparameterlinebreak) +* [Style/FirstParameterIndentation](cops_style.md/#stylefirstparameterindentation) +* [Style/FlipFlop](cops_style.md/#styleflipflop) +* [Style/For](cops_style.md/#stylefor) +* [Style/FormatString](cops_style.md/#styleformatstring) +* [Style/FrozenStringLiteralComment](cops_style.md/#stylefrozenstringliteralcomment) +* [Style/GlobalVars](cops_style.md/#styleglobalvars) +* [Style/GuardClause](cops_style.md/#styleguardclause) +* [Style/HashSyntax](cops_style.md/#stylehashsyntax) +* [Style/IdenticalConditionalBranches](cops_style.md/#styleidenticalconditionalbranches) +* [Style/IfInsideElse](cops_style.md/#styleifinsideelse) +* [Style/IfUnlessModifier](cops_style.md/#styleifunlessmodifier) +* [Style/IfUnlessModifierOfIfUnless](cops_style.md/#styleifunlessmodifierofifunless) +* [Style/IfWithSemicolon](cops_style.md/#styleifwithsemicolon) +* [Style/ImplicitRuntimeError](cops_style.md/#styleimplicitruntimeerror) +* [Style/IndentArray](cops_style.md/#styleindentarray) +* [Style/IndentAssignment](cops_style.md/#styleindentassignment) +* [Style/IndentHash](cops_style.md/#styleindenthash) +* [Style/IndentationConsistency](cops_style.md/#styleindentationconsistency) +* [Style/IndentationWidth](cops_style.md/#styleindentationwidth) +* [Style/InfiniteLoop](cops_style.md/#styleinfiniteloop) +* [Style/InitialIndentation](cops_style.md/#styleinitialindentation) +* [Style/InlineComment](cops_style.md/#styleinlinecomment) +* [Style/Lambda](cops_style.md/#stylelambda) +* [Style/LambdaCall](cops_style.md/#stylelambdacall) +* [Style/LeadingCommentSpace](cops_style.md/#styleleadingcommentspace) +* [Style/LineEndConcatenation](cops_style.md/#stylelineendconcatenation) +* [Style/MethodCallParentheses](cops_style.md/#stylemethodcallparentheses) +* [Style/MethodCalledOnDoEndBlock](cops_style.md/#stylemethodcalledondoendblock) +* [Style/MethodDefParentheses](cops_style.md/#stylemethoddefparentheses) +* [Style/MethodMissing](cops_style.md/#stylemethodmissing) +* [Style/MethodName](cops_style.md/#stylemethodname) +* [Style/MissingElse](cops_style.md/#stylemissingelse) +* [Style/ModuleFunction](cops_style.md/#stylemodulefunction) +* [Style/MultilineArrayBraceLayout](cops_style.md/#stylemultilinearraybracelayout) +* [Style/MultilineAssignmentLayout](cops_style.md/#stylemultilineassignmentlayout) +* [Style/MultilineBlockChain](cops_style.md/#stylemultilineblockchain) +* [Style/MultilineBlockLayout](cops_style.md/#stylemultilineblocklayout) +* [Style/MultilineHashBraceLayout](cops_style.md/#stylemultilinehashbracelayout) +* [Style/MultilineIfThen](cops_style.md/#stylemultilineifthen) +* [Style/MultilineMethodCallBraceLayout](cops_style.md/#stylemultilinemethodcallbracelayout) +* [Style/MultilineMethodCallIndentation](cops_style.md/#stylemultilinemethodcallindentation) +* [Style/MultilineMethodDefinitionBraceLayout](cops_style.md/#stylemultilinemethoddefinitionbracelayout) +* [Style/MultilineOperationIndentation](cops_style.md/#stylemultilineoperationindentation) +* [Style/MultilineTernaryOperator](cops_style.md/#stylemultilineternaryoperator) +* [Style/MutableConstant](cops_style.md/#stylemutableconstant) +* [Style/NegatedIf](cops_style.md/#stylenegatedif) +* [Style/NegatedWhile](cops_style.md/#stylenegatedwhile) +* [Style/NestedModifier](cops_style.md/#stylenestedmodifier) +* [Style/NestedParenthesizedCalls](cops_style.md/#stylenestedparenthesizedcalls) +* [Style/NestedTernaryOperator](cops_style.md/#stylenestedternaryoperator) +* [Style/Next](cops_style.md/#stylenext) +* [Style/NilComparison](cops_style.md/#stylenilcomparison) +* [Style/NonNilCheck](cops_style.md/#stylenonnilcheck) +* [Style/Not](cops_style.md/#stylenot) +* [Style/NumericLiteralPrefix](cops_style.md/#stylenumericliteralprefix) +* [Style/NumericLiterals](cops_style.md/#stylenumericliterals) +* [Style/NumericPredicate](cops_style.md/#stylenumericpredicate) +* [Style/OneLineConditional](cops_style.md/#styleonelineconditional) +* [Style/OpMethod](cops_style.md/#styleopmethod) +* [Style/OptionHash](cops_style.md/#styleoptionhash) +* [Style/OptionalArguments](cops_style.md/#styleoptionalarguments) +* [Style/ParallelAssignment](cops_style.md/#styleparallelassignment) +* [Style/ParenthesesAroundCondition](cops_style.md/#styleparenthesesaroundcondition) +* [Style/PercentLiteralDelimiters](cops_style.md/#stylepercentliteraldelimiters) +* [Style/PercentQLiterals](cops_style.md/#stylepercentqliterals) +* [Style/PerlBackrefs](cops_style.md/#styleperlbackrefs) +* [Style/PredicateName](cops_style.md/#stylepredicatename) +* [Style/PreferredHashMethods](cops_style.md/#stylepreferredhashmethods) +* [Style/Proc](cops_style.md/#styleproc) +* [Style/RaiseArgs](cops_style.md/#styleraiseargs) +* [Style/RedundantBegin](cops_style.md/#styleredundantbegin) +* [Style/RedundantException](cops_style.md/#styleredundantexception) +* [Style/RedundantFreeze](cops_style.md/#styleredundantfreeze) +* [Style/RedundantParentheses](cops_style.md/#styleredundantparentheses) +* [Style/RedundantReturn](cops_style.md/#styleredundantreturn) +* [Style/RedundantSelf](cops_style.md/#styleredundantself) +* [Style/RegexpLiteral](cops_style.md/#styleregexpliteral) +* [Style/RescueEnsureAlignment](cops_style.md/#stylerescueensurealignment) +* [Style/RescueModifier](cops_style.md/#stylerescuemodifier) +* [Style/SelfAssignment](cops_style.md/#styleselfassignment) +* [Style/Semicolon](cops_style.md/#stylesemicolon) +* [Style/Send](cops_style.md/#stylesend) +* [Style/SignalException](cops_style.md/#stylesignalexception) +* [Style/SingleLineBlockParams](cops_style.md/#stylesinglelineblockparams) +* [Style/SingleLineMethods](cops_style.md/#stylesinglelinemethods) +* [Style/SpaceAfterColon](cops_style.md/#stylespaceaftercolon) +* [Style/SpaceAfterComma](cops_style.md/#stylespaceaftercomma) +* [Style/SpaceAfterMethodName](cops_style.md/#stylespaceaftermethodname) +* [Style/SpaceAfterNot](cops_style.md/#stylespaceafternot) +* [Style/SpaceAfterSemicolon](cops_style.md/#stylespaceaftersemicolon) +* [Style/SpaceAroundBlockParameters](cops_style.md/#stylespacearoundblockparameters) +* [Style/SpaceAroundEqualsInParameterDefault](cops_style.md/#stylespacearoundequalsinparameterdefault) +* [Style/SpaceAroundKeyword](cops_style.md/#stylespacearoundkeyword) +* [Style/SpaceAroundOperators](cops_style.md/#stylespacearoundoperators) +* [Style/SpaceBeforeBlockBraces](cops_style.md/#stylespacebeforeblockbraces) +* [Style/SpaceBeforeComma](cops_style.md/#stylespacebeforecomma) +* [Style/SpaceBeforeComment](cops_style.md/#stylespacebeforecomment) +* [Style/SpaceBeforeFirstArg](cops_style.md/#stylespacebeforefirstarg) +* [Style/SpaceBeforeSemicolon](cops_style.md/#stylespacebeforesemicolon) +* [Style/SpaceInsideArrayPercentLiteral](cops_style.md/#stylespaceinsidearraypercentliteral) +* [Style/SpaceInsideBlockBraces](cops_style.md/#stylespaceinsideblockbraces) +* [Style/SpaceInsideBrackets](cops_style.md/#stylespaceinsidebrackets) +* [Style/SpaceInsideHashLiteralBraces](cops_style.md/#stylespaceinsidehashliteralbraces) +* [Style/SpaceInsideParens](cops_style.md/#stylespaceinsideparens) +* [Style/SpaceInsidePercentLiteralDelimiters](cops_style.md/#stylespaceinsidepercentliteraldelimiters) +* [Style/SpaceInsideRangeLiteral](cops_style.md/#stylespaceinsiderangeliteral) +* [Style/SpaceInsideStringInterpolation](cops_style.md/#stylespaceinsidestringinterpolation) +* [Style/SpecialGlobalVars](cops_style.md/#stylespecialglobalvars) +* [Style/StabbyLambdaParentheses](cops_style.md/#stylestabbylambdaparentheses) +* [Style/StringLiterals](cops_style.md/#stylestringliterals) +* [Style/StringLiteralsInInterpolation](cops_style.md/#stylestringliteralsininterpolation) +* [Style/StringMethods](cops_style.md/#stylestringmethods) +* [Style/StructInheritance](cops_style.md/#stylestructinheritance) +* [Style/SymbolArray](cops_style.md/#stylesymbolarray) +* [Style/SymbolLiteral](cops_style.md/#stylesymbolliteral) +* [Style/SymbolProc](cops_style.md/#stylesymbolproc) +* [Style/Tab](cops_style.md/#styletab) +* [Style/TernaryParentheses](cops_style.md/#styleternaryparentheses) +* [Style/TrailingBlankLines](cops_style.md/#styletrailingblanklines) +* [Style/TrailingCommaInArguments](cops_style.md/#styletrailingcommainarguments) +* [Style/TrailingCommaInLiteral](cops_style.md/#styletrailingcommainliteral) +* [Style/TrailingUnderscoreVariable](cops_style.md/#styletrailingunderscorevariable) +* [Style/TrailingWhitespace](cops_style.md/#styletrailingwhitespace) +* [Style/TrivialAccessors](cops_style.md/#styletrivialaccessors) +* [Style/UnlessElse](cops_style.md/#styleunlesselse) +* [Style/UnneededCapitalW](cops_style.md/#styleunneededcapitalw) +* [Style/UnneededInterpolation](cops_style.md/#styleunneededinterpolation) +* [Style/UnneededPercentQ](cops_style.md/#styleunneededpercentq) +* [Style/VariableInterpolation](cops_style.md/#stylevariableinterpolation) +* [Style/VariableName](cops_style.md/#stylevariablename) +* [Style/WhenThen](cops_style.md/#stylewhenthen) +* [Style/WhileUntilDo](cops_style.md/#stylewhileuntildo) +* [Style/WhileUntilModifier](cops_style.md/#stylewhileuntilmodifier) +* [Style/WordArray](cops_style.md/#stylewordarray) +* [Style/ZeroLengthPredicate](cops_style.md/#stylezerolengthpredicate) diff --git a/manual/cops_lint.md b/manual/cops_lint.md new file mode 100644 index 000000000000..342a2c775d94 --- /dev/null +++ b/manual/cops_lint.md @@ -0,0 +1,1180 @@ +# Lint + +## Lint/AmbiguousOperator + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for ambiguous operators in the first argument of a +method invocation without parentheses. + +### Example + +```ruby +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 + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for ambiguous regexp literals in the first argument of +a method invocation without parentheses. + +### Example + +```ruby +# 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 + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for assignments in the conditions of +if/while/until. + +### Important attributes + +Attribute | Value | +--- | --- | +AllowSafeAssignment | true| | + + +## Lint/BlockAlignment + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks whether the end keywords are aligned properly for do +end blocks. + +Three modes are supported through the `AlignWith` configuration +parameter: + +`start_of_block` : the `end` shall be aligned with the +start of the line where the `do` appeared. + +`start_of_line` : the `end` shall be aligned with the +start of the line where the expression started. + +`either` (which is the default) : the `end` is allowed to be in either +location. The autofixer will default to `start_of_line`. + +### Example + +```ruby +# either +variable = lambda do |i| + i +end + +# start_of_block +foo.bar + .each do + baz + end + +# start_of_line +foo.bar + .each do + baz +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AlignWith | either| | +SupportedStyles | either, start_of_block, start_of_line| | + + +## Lint/CircularArgumentReference + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for circular argument references in optional keyword +arguments and optional ordinal arguments. + +This cop mirrors a warning produced by MRI since 2.2. + +### Example + +```ruby +# bad +def bake(pie: pie) + pie.heat_up +end + +# good +def bake(pie:) + pie.refrigerate +end + +# good +def bake(pie: self.pie) + pie.feed_to(user) +end + +# bad +def cook(dry_ingredients = dry_ingredients) + dry_ingredients.reduce(&:+) +end + +# good +def cook(dry_ingredients = self.dry_ingredients) + dry_ingredients.combine +end +``` + +## Lint/ConditionPosition + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for conditions that are not on the same line as +if/while/until. + +### Example + +```ruby +if + some_condition + do_something +end +``` + +## Lint/Debugger + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for calls to debugger or pry. + +## Lint/DefEndAlignment + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks whether the end keywords of method definitions are +aligned properly. + +Two modes are supported through the AlignWith configuration +parameter. If it's set to `start_of_line` (which is the default), the +`end` shall be aligned with the start of the line where the `def` +keyword is. If it's set to `def`, the `end` shall be aligned with the +`def` keyword. + +### Example + +```ruby +private def foo +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AlignWith | start_of_line| | +SupportedStyles | start_of_line, def| | +AutoCorrect | false| | + + +## Lint/DeprecatedClassMethods + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for uses of the deprecated class method usages. + +## Lint/DuplicateMethods + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for duplicated instance (or singleton) method +definitions. + +### Example + +```ruby +# bad +def duplicated + 1 +end + +def duplicated + 2 +end +``` + +## Lint/DuplicatedKey + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for duplicated keys in hash literals. + +This cop mirrors a warning in Ruby 2.2. + +### Example + +```ruby +hash = { food: 'apple', food: 'orange' } +``` + +## Lint/EachWithObjectArgument + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks if each_with_object is called with an immutable +argument. Since the argument is the object that the given block shall +make calls on to build something based on the enumerable that +each_with_object iterates over, an immutable argument makes no sense. +It's definitely a bug. + +### Example + +```ruby +sum = numbers.each_with_object(0) { |e, a| a += e } +``` + +## Lint/ElseLayout + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for odd else block layout - like +having an expression on the same line as the else keyword, +which is usually a mistake. + +### Example + +```ruby +if something + ... +else do_this + do_that +end +``` + +## Lint/EmptyEnsure + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for empty `ensure` blocks + +## Lint/EmptyInterpolation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for empty interpolation. + +### Example + +```ruby +"result is #{}" +``` + +## Lint/EndAlignment + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks whether the end keywords are aligned properly. + +Three modes are supported through the `AlignWith` configuration +parameter: + +If it's set to `keyword` (which is the default), the `end` +shall be aligned with the start of the keyword (if, class, etc.). + +If it's set to `variable` the `end` shall be aligned with the +left-hand-side of the variable assignment, if there is one. + +If it's set to `start_of_line`, the `end` shall be aligned with the +start of the line where the matching keyword appears. + +### Example + +```ruby +# good +# keyword style +variable = if true + end + +# variable style +variable = if true +end + +# start_of_line style +puts(if true +end) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AlignWith | keyword| | +SupportedStyles | keyword, variable, start_of_line| | +AutoCorrect | false| | + + +## Lint/EndInMethod + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for END blocks in method definitions. + +## Lint/EnsureReturn + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for *return* from an *ensure* block. + +## Lint/Eval + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for the use of *Kernel#eval*. + +## Lint/FloatOutOfRange + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop identifies Float literals which are, like, really really really +really really really really really big. Too big. No-one needs Floats +that big. If you need a float that big, something is wrong with you. + +### Example + +```ruby +# bad +float = 3.0e400 + +# good +float = 42.9 +``` + +## Lint/FormatParameterMismatch + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This lint sees if there is a mismatch between the number of +expected fields for format/sprintf/#% and what is actually +passed as arguments. + +### Example + +```ruby +format('A value: %s and another: %i', a_value) +``` + +## Lint/HandleExceptions + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for *rescue* blocks with no body. + +## Lint/ImplicitStringConcatenation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for implicit string concatenation of string literals +which are on the same line. + +### Example + +```ruby +# bad +array = ['Item 1' 'Item 2'] + +# good +array = ['Item 1Item 2'] +array = ['Item 1' + 'Item 2'] +array = [ + 'Item 1' \ + 'Item 2' +] +``` + +## Lint/IneffectiveAccessModifier + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for `private` or `protected` access modifiers which are +applied to a singleton method. These access modifiers do not make +singleton methods private/protected. `private_class_method` can be +used for that. + +### Example + +```ruby +# bad +class C + private + + def self.method + puts 'hi' + end +end + +# good +class C + def self.method + puts 'hi' + end + + private_class_method :method +end + +class C + class << self + private + + def method + puts 'hi' + end + end +end +``` + +## Lint/InheritException + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop looks for error classes inheriting from `Exception` +and its standard library subclasses, excluding subclasses of +`StandardError`. It is configurable to suggest using either +`RuntimeError` (default) or `StandardError` instead. + +### Example + +```ruby +# bad + +class C < Exception; end +``` +```ruby +# EnforcedStyle: runtime_error (default) + +# good + +class C < RuntimeError; end +``` +```ruby +# EnforcedStyle: standard_error + +# good + +class C < StandardError; end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | runtime_error| | +SupportedStyles | runtime_error, standard_error| | + + +## Lint/InvalidCharacterLiteral + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for invalid character literals with a non-escaped +whitespace character (e.g. `? `). +However, currently it's unclear whether there's a way to emit this +warning without syntax errors. + + $ ruby -w + p(? ) + -:1: warning: invalid character syntax; use ?\s + -:1: syntax error, unexpected '?', expecting ')' + p(? ) + ^ + +### Example + +```ruby +p(? ) +``` + +## Lint/LiteralInCondition + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for literals used as the conditions or as +operands in and/or expressions serving as the conditions of +if/while/until. + +### Example + +```ruby +if 20 + do_something +end + +if some_var && true + do_something +end +``` + +## Lint/LiteralInInterpolation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for interpolated literals. + +### Example + +```ruby +"result is #{10}" +``` + +## Lint/Loop + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for uses of *begin...end while/until something*. + +## Lint/NestedMethodDefinition + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for nested method definitions. + +### Example + +```ruby +# `bar` definition actually produces methods in the same scope +# as the outer `foo` method. Furthermore, the `bar` method +# will be redefined every time `foo` is invoked. +def foo + def bar + end +end +``` + +## Lint/NextWithoutAccumulator + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +Don't omit the accumulator when calling `next` in a `reduce` block. + +### Example + +```ruby +# bad +result = (1..4).reduce(0) do |acc, i| + next if i.odd? + acc + i +end + +# good +result = (1..4).reduce(0) do |acc, i| + next acc if i.odd? + acc + i +end +``` + +## Lint/NonLocalExitFromIterator + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for non-local exit from iterator, without return value. +It warns only when satisfies all of these: `return` doesn't have return +value, the block is preceded by a method chain, the block has arguments, +and the method which receives the block is not `define_method`. + +### Example + +```ruby +class ItemApi + rescue_from ValidationError do |e| # non-iteration block with arg + return message: 'validation error' unless e.errors # allowed + error_array = e.errors.map do |error| # block with method chain + return if error.suppress? # warned + return "#{error.param}: invalid" unless error.message # allowed + "#{error.param}: #{error.message}" + end + message: 'validation error', errors: error_array + end + + def update_items + transaction do # block without arguments + return unless update_necessary? # allowed + find_each do |item| # block without method chain + return if item.stock == 0 # false-negative... + item.update!(foobar: true) + end + end + end +end +``` + +## Lint/ParenthesesAsGroupedExpression + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +Checks for space between a the name of a called method and a left +parenthesis. + +### Example + +```ruby +puts (x + y) +``` + +## Lint/PercentStringArray + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for quotes and commas in %w, e.g. + + `%w('foo', "bar")` + +it is more likely that the additional characters are unintended (for +example, mistranslating an array of literals to percent string notation) +rather than meant to be part of the resulting strings. + +## Lint/PercentSymbolArray + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for colons and commas in %i, e.g. + + `%i(:foo, :bar)` + +it is more likely that the additional characters are unintended (for +example, mistranslating an array of literals to percent string notation) +rather than meant to be part of the resulting symbols. + +## Lint/RandOne + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for `rand(1)` calls. +Such calls always return `0`. + +### Example + +```ruby +# bad +rand 1 +Kernel.rand(-1) +rand 1.0 +rand(-1.0) + +# good +0 +``` + +## Lint/RequireParentheses + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for expressions where there is a call to a predicate +method with at least one argument, where no parentheses are used around +the parameter list, and a boolean operator, && or ||, is used in the +last argument. + +The idea behind warning for these constructs is that the user might +be under the impression that the return value from the method call is +an operand of &&/||. + +### Example + +```ruby +if day.is? :tuesday && month == :jan + ... +end +``` + +## Lint/RescueException + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for *rescue* blocks targeting the Exception class. + +## Lint/ShadowedException + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for a rescued exception that get shadowed by a +less specific exception being rescued before a more specific +exception is rescued. + +### Example + +```ruby +# bad +begin + something +rescue Exception + handle_exception +rescue StandardError + handle_standard_error +end + +# good +begin + something +rescue StandardError + handle_standard_error +rescue Exception + handle_exception +end +``` + +## Lint/ShadowingOuterLocalVariable + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop looks for use of the same name as outer local variables +for block arguments or block local variables. +This is a mimic of the warning +"shadowing outer local variable - foo" from `ruby -cw`. + +## Lint/StringConversionInInterpolation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for string conversion in string interpolation, +which is redundant. + +### Example + +```ruby +"result is #{something.to_s}" +``` + +## Lint/UnderscorePrefixedVariableName + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for underscore-prefixed variables that are actually +used. + +## Lint/UnifiedInteger + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for using Fixnum or Bignum constant. + +### Example + +```ruby +# bad +1.is_a?(Fixnum) +1.is_a?(Bignum) + +# good +1.is_a?(Integer) +``` + +## Lint/UnneededDisable + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop detects instances of rubocop:disable comments that can be +removed without causing any offenses to be reported. It's implemented +as a cop in that it inherits from the Cop base class and calls +add_offense. The unusual part of its implementation is that it doesn't +have any on_* methods or an investigate method. This means that it +doesn't take part in the investigation phase when the other cops do +their work. Instead, it waits until it's called in a later stage of the +execution. The reason it can't be implemented as a normal cop is that +it depends on the results of all other cops to do its work. + +## Lint/UnneededSplatExpansion + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for unneeded usages of splat expansion + +### Example + +```ruby +# bad +a = *[1, 2, 3] +a = *'a' +a = *1 + +begin + foo +rescue *[StandardError, ApplicationError] + bar +end + +case foo +when *[1, 2, 3] + bar +else + baz +end + +# good +c = [1, 2, 3] +a = *c +a, b = *c +a, *b = *c +a = *1..10 +a = ['a'] + +begin + foo +rescue StandardError, ApplicationError + bar +end + +case foo +when *[1, 2, 3] + bar +else + baz +end +``` + +## Lint/UnreachableCode + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for unreachable code. +The check are based on the presence of flow of control +statement in non-final position in *begin*(implicit) blocks. + +## Lint/UnusedBlockArgument + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for unused block arguments. + +### Example + +```ruby +#good + +do_something do |used, unused| + puts used +end + +do_something do + puts :foo +end + +define_method(:foo) do |_bar| + puts :baz +end + +# bad + +do_something do |used, _unused| + puts used +end + +do_something do |bar| + puts :foo +end + +define_method(:foo) do |bar| + puts :baz +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +IgnoreEmptyBlocks | true| | +AllowUnusedKeywordArguments | false| | + + +## Lint/UnusedMethodArgument + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for unused method arguments. + +### Example + +```ruby +def some_method(used, unused, _unused_but_allowed) + puts used +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AllowUnusedKeywordArguments | false| | +IgnoreEmptyMethods | true| | + + +## Lint/UselessAccessModifier + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for redundant access modifiers, including those with no +code, those which are repeated, and leading `public` modifiers in a +class or module body. Conditionally-defined methods are considered as +always being defined, and thus access modifiers guarding such methods +are not redundant. + +### Example + +```ruby +class Foo + public # this is redundant (default access is public) + + def method + end + + private # this is not redundant (a method is defined) + def method2 + end + + private # this is redundant (no following methods are defined) +end +``` +```ruby +class Foo + # The following is not redundant (conditionally defined methods are + # considered as always defining a method) + private + + if condition? + def method + end + end + + protected # this is not redundant (method is defined) + + define_method(:method2) do + end + + protected # this is redundant (repeated from previous modifier) + + [1,2,3].each do |i| + define_method("foo#{i}") do + end + end + + # The following is redundant (methods defined on the class' + # singleton class are not affected by the public modifier) + public + + def self.method3 + end +end +``` +```ruby +# Lint/UselessAccessModifier: +# ContextCreatingMethods: +# - concerning +require 'active_support/concern' +class Foo + concerning :Bar do + def some_public_method + end + + private + + def some_private_method + end + end + + # this is not redundant because `concerning` created its own context + private + + def some_other_private_method + end +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +ContextCreatingMethods | | | + + +## Lint/UselessAssignment + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for every useless assignment to local variable in every +scope. +The basic idea for this cop was from the warning of `ruby -cw`: + + assigned but unused variable - foo + +Currently this cop has advanced logic that detects unreferenced +reassignments and properly handles varied cases such as branch, loop, +rescue, ensure, etc. + +## Lint/UselessComparison + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for comparison of something with itself. + +### Example + +```ruby +x.top >= x.top +``` + +## Lint/UselessElseWithoutRescue + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for useless `else` in `begin..end` without `rescue`. + +### Example + +```ruby +begin + do_something +else + handle_errors # This will never be run. +end +``` + +## Lint/UselessSetterCall + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for setter call to local variable as the final +expression of a function definition. + +### Example + +```ruby +def something + x = Something.new + x.attr = 5 +end +``` + +## Lint/Void + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for operators, variables and literals used +in void context. diff --git a/manual/cops_metrics.md b/manual/cops_metrics.md new file mode 100644 index 000000000000..6b5a6a26c024 --- /dev/null +++ b/manual/cops_metrics.md @@ -0,0 +1,213 @@ +# Metrics + +## Metrics/AbcSize + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks that the ABC size of methods is not higher than the +configured maximum. The ABC size is based on assignments, branches +(method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | http://c2.com/cgi/wiki?AbcMetric| | +Max | 19| | + + +## Metrics/BlockLength + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks if the length of a block exceeds some maximum value. +Comment lines can optionally be ignored. +The maximum allowed length is configurable. + +### Important attributes + +Attribute | Value | +--- | --- | +CountComments | false| | +Max | 25| | +Exclude | /Rakefile, /**/*.rake, /spec/**/*.rb| | + + +## Metrics/BlockNesting + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for excessive nesting of conditional and looping +constructs. Despite the cop's name, blocks are not considered as an +extra level of nesting. + +The maximum level of nesting allowed is configurable. + +### Important attributes + +Attribute | Value | +--- | --- | +Max | 3| | + + +## Metrics/ClassLength + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks if the length a class exceeds some maximum value. +Comment lines can optionally be ignored. +The maximum allowed length is configurable. + +### Important attributes + +Attribute | Value | +--- | --- | +CountComments | false| | +Max | 168| | + + +## Metrics/CyclomaticComplexity + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks that the cyclomatic complexity of methods is not higher +than the configured maximum. The cyclomatic complexity is the number of +linearly independent paths through a method. The algorithm counts +decision points and adds one. + +An if statement (or unless or ?:) increases the complexity by one. An +else branch does not, since it doesn't add a decision point. The && +operator (or keyword and) can be converted to a nested if statement, +and ||/or is shorthand for a sequence of ifs, so they also add one. +Loops can be said to have an exit condition, so they add one. + +### Important attributes + +Attribute | Value | +--- | --- | +Max | 7| | + + +## Metrics/LineLength + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks the length of lines in the source code. +The maximum length is configurable. + +### Important attributes + +Attribute | Value | +--- | --- | +Max | 80| | +AllowHeredoc | true| | +AllowURI | true| | +URISchemes | http, https| | +IgnoreCopDirectives | false| | + + +## Metrics/MethodLength + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks if the length of a method exceeds some maximum value. +Comment lines can optionally be ignored. +The maximum allowed length is configurable. + +### Important attributes + +Attribute | Value | +--- | --- | +CountComments | false| | +Max | 14| | + + +## Metrics/ModuleLength + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks if the length a module exceeds some maximum value. +Comment lines can optionally be ignored. +The maximum allowed length is configurable. + +### Important attributes + +Attribute | Value | +--- | --- | +CountComments | false| | +Max | 156| | + + +## Metrics/ParameterLists + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for methods with too many parameters. +The maximum number of parameters is configurable. +On Ruby 2.0+ keyword arguments can optionally +be excluded from the total count. + +### Important attributes + +Attribute | Value | +--- | --- | +Max | 5| | +CountKeywordArgs | true| | + + +## Metrics/PerceivedComplexity + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop tries to produce a complexity score that's a measure of the +complexity the reader experiences when looking at a method. For that +reason it considers `when` nodes as something that doesn't add as much +complexity as an `if` or a `&&`. Except if it's one of those special +`case`/`when` constructs where there's no expression after `case`. Then +the cop treats it as an `if`/`elsif`/`elsif`... and lets all the `when` +nodes count. In contrast to the CyclomaticComplexity cop, this cop +considers `else` nodes as adding complexity. + +### Example + +```ruby +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 +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Max | 7| | + diff --git a/manual/cops_performance.md b/manual/cops_performance.md new file mode 100644 index 000000000000..27ee1e8b8787 --- /dev/null +++ b/manual/cops_performance.md @@ -0,0 +1,660 @@ +# Performance + +## Performance/CaseWhenSplat + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Place `when` conditions that use splat at the end +of the list of `when` branches. + +Ruby has to allocate memory for the splat expansion every time +that the `case` `when` statement is run. Since Ruby does not support +fall through inside of `case` `when`, like some other languages do, +the order of the `when` branches does not matter. By placing any +splat expansions at the end of the list of `when` branches we will +reduce the number of times that memory has to be allocated for +the expansion. + +This is not a guaranteed performance improvement. If the data being +processed by the `case` condition is normalized in a manner that favors +hitting a condition in the splat expansion, it is possible that +moving the splat condition to the end will use more memory, +and run slightly slower. + +### Example + +```ruby +# bad +case foo +when *condition + bar +when baz + foobar +end + +case foo +when *[1, 2, 3, 4] + bar +when 5 + baz +end + +# good +case foo +when baz + foobar +when *condition + bar +end + +case foo +when 1, 2, 3, 4 + bar +when 5 + baz +end +``` + +## Performance/Casecmp + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop identifies places where a case-insensitive string comparison +can better be implemented using `casecmp`. + +### Example + +```ruby +# bad +str.downcase == 'abc' +str.upcase.eql? 'ABC' +'abc' == str.downcase +'ABC'.eql? str.upcase +str.downcase == str.downcase + +# good +str.casecmp('ABC').zero? +'abc'.casecmp(str).zero? +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#stringcasecmp-vs-stringdowncase---code| | + + +## Performance/Count + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is used to identify usages of `count` on an `Enumerable` that +follow calls to `select` or `reject`. Querying logic can instead be +passed to the `count` call. + +`ActiveRecord` compatibility: +`ActiveRecord` will ignore the block that is passed to `count`. +Other methods, such as `select`, will convert the association to an +array and then run the block on the array. A simple work around to +make `count` work with a block is to call `to_a.count {...}`. + +Example: + Model.where(id: [1, 2, 3].select { |m| m.method == true }.size + + becomes: + + Model.where(id: [1, 2, 3]).to_a.count { |m| m.method == true } + +### Example + +```ruby +# bad +[1, 2, 3].select { |e| e > 2 }.size +[1, 2, 3].reject { |e| e > 2 }.size +[1, 2, 3].select { |e| e > 2 }.length +[1, 2, 3].reject { |e| e > 2 }.length +[1, 2, 3].select { |e| e > 2 }.count { |e| e.odd? } +[1, 2, 3].reject { |e| e > 2 }.count { |e| e.even? } +array.select(&:value).count + +# good +[1, 2, 3].count { |e| e > 2 } +[1, 2, 3].count { |e| e < 2 } +[1, 2, 3].count { |e| e > 2 && e.odd? } +[1, 2, 3].count { |e| e < 2 && e.even? } +Model.select('field AS field_one').count +Model.select(:value).count +``` + +### Important attributes + +Attribute | Value | +--- | --- | +SafeMode | true| | + + +## Performance/Detect + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is used to identify usages of +`select.first`, `select.last`, `find_all.first`, and `find_all.last` +and change them to use `detect` instead. + +`ActiveRecord` compatibility: +`ActiveRecord` does not implement a `detect` method and `find` has its +own meaning. Correcting ActiveRecord methods with this cop should be +considered unsafe. + +### Example + +```ruby +# bad +[].select { |item| true }.first +[].select { |item| true }.last +[].find_all { |item| true }.first +[].find_all { |item| true }.last + +# good +[].detect { |item| true } +[].reverse.detect { |item| true } +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#enumerabledetect-vs-enumerableselectfirst-code| | +SafeMode | true| | + + +## Performance/DoubleStartEndWith + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for double `#start_with?` or `#end_with?` calls +separated by `||`. In some cases such calls can be replaced +with an single `#start_with?`/`#end_with?` call. + +### Example + +```ruby +# bad +str.start_with?("a") || str.start_with?(Some::CONST) +str.start_with?("a", "b") || str.start_with?("c") +var1 = ... +var2 = ... +str.end_with?(var1) || str.end_with?(var2) + +# good +str.start_with?("a", Some::CONST) +str.start_with?("a", "b", "c") +var1 = ... +var2 = ... +str.end_with?(var1, var2) +``` + +## Performance/EndWith + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop identifies unnecessary use of a regex where `String#end_with?` +would suffice. + +### Example + +```ruby +# bad +'abc' =~ /bc\Z/ +'abc'.match(/bc\Z/) + +# good +'abc' =~ /ab/ +'abc' =~ /\w*\Z/ +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#stringmatch-vs-stringstart_withstringend_with-code-start-code-end| | +AutoCorrect | false| | + + +## Performance/FixedSize + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +Do not compute the size of statically sized objects. + +## Performance/FlatMap + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is used to identify usages of + +### Example + +```ruby +# bad +[1, 2, 3, 4].map { |e| [e, e] }.flatten(1) +[1, 2, 3, 4].collect { |e| [e, e] }.flatten(1) + +# good +[1, 2, 3, 4].flat_map { |e| [e, e] } +[1, 2, 3, 4].map { |e| [e, e] }.flatten +[1, 2, 3, 4].collect { |e| [e, e] }.flatten +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#enumerablemaparrayflatten-vs-enumerableflat_map-code| | +EnabledForFlattenWithoutParams | false| | + + +## Performance/HashEachMethods + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for uses of `each_key` & `each_value` Hash methods. + +### Example + +```ruby +# bad +hash.keys.each { |k| p k } +hash.values.each { |v| p v } +hash.each { |k, _v| p k } +hash.each { |_k, v| p v } + +# good +hash.each_key { |k| p k } +hash.each_value { |v| p v } +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AutoCorrect | false| | + + +## Performance/LstripRstrip + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop identifies places where `lstrip.rstrip` can be replaced by +`strip`. + +### Example + +```ruby +# bad +'abc'.lstrip.rstrip +'abc'.rstrip.lstrip + +# good +'abc'.strip +``` + +## Performance/RangeInclude + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop identifies uses of `Range#include?`, which iterates over each +item in a `Range` to see if a specified item is there. In contrast, +`Range#cover?` simply compares the target item with the beginning and +end points of the `Range`. In a great majority of cases, this is what +is wanted. + +Here is an example of a case where `Range#cover?` may not provide the +desired result: + + ('a'..'z').cover?('yellow') # => true + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#cover-vs-include-code| | + + +## Performance/RedundantBlockCall + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop identifies the use of a `&block` parameter and `block.call` +where `yield` would do just as well. + +### Example + +```ruby +# bad +def method(&block) + block.call +end +def another(&func) + func.call 1, 2, 3 +end + +# good +def method + yield +end +def another + yield 1, 2, 3 +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#proccall-vs-yield-code| | + + +## Performance/RedundantMatch + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop identifies use of `Regexp#match` or `String#match in a context +where the integral return value of `=~` would do just as well. + +### Example + +```ruby +# bad +do_something if str.match(/regex/) +while regex.match('str') + do_something +end + +# good +method(str.match(/regex/)) +return regex.match('str') +``` + +## Performance/RedundantMerge + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop identifies places where `Hash#merge!` can be replaced by +`Hash#[]=`. + +### Example + +```ruby +hash.merge!(a: 1) +hash.merge!({'key' => 'value'}) +hash.merge!(a: 1, b: 2) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#hashmerge-vs-hash-code| | +MaxKeyValuePairs | 2| | + + +## Performance/RedundantSortBy + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop identifies places where `sort_by { ... }` can be replaced by +`sort`. + +### Example + +```ruby +# bad +array.sort_by { |x| x } +array.sort_by do |var| + var +end + +# good +array.sort +``` + +## Performance/ReverseEach + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is used to identify usages of `reverse.each` and +change them to use `reverse_each` instead. + +### Example + +```ruby +# bad +[].reverse.each + +# good +[].reverse_each +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#enumerablereverseeach-vs-enumerablereverse_each-code| | + + +## Performance/Sample + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is used to identify usages of `shuffle.first`, `shuffle.last` +and `shuffle[]` and change them to use `sample` instead. + +### Example + +```ruby +# bad +[1, 2, 3].shuffle.first +[1, 2, 3].shuffle.first(2) +[1, 2, 3].shuffle.last +[1, 2, 3].shuffle[2] +[1, 2, 3].shuffle[0, 2] # sample(2) will do the same +[1, 2, 3].shuffle[0..2] # sample(3) will do the same +[1, 2, 3].shuffle(random: Random.new).first + +# good +[1, 2, 3].shuffle +[1, 2, 3].sample +[1, 2, 3].sample(3) +[1, 2, 3].shuffle[1, 3] # sample(3) might return a longer Array +[1, 2, 3].shuffle[1..3] # sample(3) might return a longer Array +[1, 2, 3].shuffle[foo, bar] +[1, 2, 3].shuffle(random: Random.new) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#arrayshufflefirst-vs-arraysample-code| | + + +## Performance/Size + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is used to identify usages of `count` on an +`Array` and `Hash` and change them to `size`. + +TODO: Add advanced detection of variables that could +have been assigned to an array or a hash. + +### Example + +```ruby +# bad +[1, 2, 3].count + +# bad +{a: 1, b: 2, c: 3}.count + +# good +[1, 2, 3].size + +# good +{a: 1, b: 2, c: 3}.size + +# good +[1, 2, 3].count { |e| e > 2 } +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#arraycount-vs-arraysize-code| | + + +## Performance/SortWithBlock + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop identifies places where `sort { |a, b| a.foo <=> b.foo }` +can be replaced by `sort_by(&:foo)`. + +### Example + +```ruby +# bad +array.sort { |a, b| a.foo <=> b.foo } + +# good +array.sort_by(&:foo) +array.sort_by { |v| v.foo } +array.sort_by do |var| + var.foo +end +``` + +## Performance/StartWith + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop identifies unnecessary use of a regex where +`String#start_with?` would suffice. + +### Example + +```ruby +# bad +'abc' =~ /\Aab/ +'abc'.match(/\Aab/) + +# good +'abc' =~ /ab/ +'abc' =~ /\A\w*/ +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#stringmatch-vs-stringstart_withstringend_with-code-start-code-end| | +AutoCorrect | false| | + + +## Performance/StringReplacement + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop identifies places where `gsub` can be replaced by +`tr` or `delete`. + +### Example + +```ruby +# bad +'abc'.gsub('b', 'd') +'abc'.gsub('a', '') +'abc'.gsub(/a/, 'd') +'abc'.gsub!('a', 'd') + +# good +'abc'.gsub(/.*/, 'a') +'abc'.gsub(/a+/, 'd') +'abc'.tr('b', 'd') +'a b c'.delete(' ') +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | https://github.com/JuanitoFatas/fast-ruby#stringgsub-vs-stringtr-code| | + + +## Performance/TimesMap + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for .times.map calls. +In most cases such calls can be replaced +with an explicit array creation. + +### Example + +```ruby +# bad +9.times.map do |i| + i.to_s +end + +# good +Array.new(9) do |i| + i.to_s +end +``` diff --git a/manual/cops_rails.md b/manual/cops_rails.md new file mode 100644 index 000000000000..7bb1b416ecc9 --- /dev/null +++ b/manual/cops_rails.md @@ -0,0 +1,658 @@ +# Rails + +## Rails/ActionFilter + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop enforces the consistent use of action filter methods. + +The cop is configurable and can enforce the use of the older +something_filter methods or the newer something_action methods. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | action| | +SupportedStyles | action, filter| | +Include | app/controllers/**/*.rb| | + + +## Rails/Date + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for the correct use of Date methods, +such as Date.today, Date.current etc. + +Using Date.today is dangerous, because it doesn't know anything about +Rails time zone. You must use Time.zone.today instead. + +The cop also reports warnings when you are using 'to_time' method, +because it doesn't know about Rails time zone either. + +Two styles are supported for this cop. When EnforcedStyle is 'strict' +then the Date methods (today, current, yesterday, tomorrow) +are prohibited and the usage of both 'to_time' +and 'to_time_in_current_zone' is reported as warning. + +When EnforcedStyle is 'flexible' then only 'Date.today' is prohibited +and only 'to_time' is reported as warning. + +### Example + +```ruby +# no offense +Time.zone.today +Time.zone.today - 1.day + +# acceptable +Date.current +Date.yesterday + +# always reports offense +Date.today +date.to_time + +# reports offense only when style is 'strict' +date.to_time_in_current_zone +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | flexible| | +SupportedStyles | strict, flexible| | + + +## Rails/Delegate + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop looks for delegations, that could have been created +automatically with delegate method. + +### Example + +```ruby +# bad +def bar + foo.bar +end + +# good +delegate :bar, to: :foo + +# bad +def foo_bar + foo.bar +end + +# good +delegate :bar, to: :foo, prefix: true + +# good +private +def bar + foo.bar +end +``` + +## Rails/DelegateAllowBlank + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop looks for delegations that pass :allow_blank as an option +instead of :allow_nil. :allow_blank is not a valid option to pass +to ActiveSupport#delegate. + +### Example + +```ruby +# bad +delegate :foo, to: :bar, allow_blank: true + +# good +delegate :foo, to: :bar, allow_nil: true +``` + +## Rails/DynamicFindBy + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks dynamic `find_by_*` methods. +Use `find_by` instead of dynamic method. +See. https://github.com/bbatsov/rails-style-guide#find_by + +### Example + +```ruby +# bad +User.find_by_name(name) + +# bad +User.find_by_name_and_email(name) + +# bad +User.find_by_email!(name) + +# good +User.find_by(name: name) + +# good +User.find_by(name: name, email: email) + +# good +User.find_by!(email: email) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Whitelist | find_by_sql| | + + +## Rails/Exit + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop enforces that 'exit' calls are not used within a rails app. +Valid options are instead to raise an error, break, return or some +other form of stopping execution of current request. + +There are two obvious cases where 'exit' is particularly harmful: + +- Usage in library code for your application. Even though rails will +rescue from a SystemExit and continue on, unit testing that library +code will result in specs exiting (potentially silently if exit(0) +is used.) +- Usage in application code outside of the web process could result in +the program exiting, which could result in the code failing to run and +do its job. + +### Important attributes + +Attribute | Value | +--- | --- | +Include | app/**/*.rb, config/**/*.rb, lib/**/*.rb| | +Exclude | /lib/**/*.rake| | + + +## Rails/FindBy + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is used to identify usages of `where.first` and +change them to use `find_by` instead. + +### Example + +```ruby +# bad +User.where(name: 'Bruce').first +User.where(name: 'Bruce').take + +# good +User.find_by(name: 'Bruce') +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Include | app/models/**/*.rb| | + + +## Rails/FindEach + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is used to identify usages of `all.each` and +change them to use `all.find_each` instead. + +### Example + +```ruby +# bad +User.all.each + +# good +User.all.find_each +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Include | app/models/**/*.rb| | + + +## Rails/HasAndBelongsToMany + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for the use of the has_and_belongs_to_many macro. + +### Important attributes + +Attribute | Value | +--- | --- | +Include | app/models/**/*.rb| | + + +## Rails/HttpPositionalArguments + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is used to identify usages of http methods +like `get`, `post`, `put`, `path` without the usage of keyword arguments +in your tests and change them to use keyword arguments. + +### Example + +```ruby +# bad +get :new, { user_id: 1} + +# good +get :new, params: { user_id: 1 } +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Include | spec/**/*, test/**/*| | + + +## Rails/NotNullColumn + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for add_column call with NOT NULL constraint +in migration file. + +### Example + +```ruby +# bad +add_column :users, :name, :string, null: false + +# good +add_column :users, :name, :string, null: true +add_column :users, :name, :string, null: false, default: '' +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Include | db/migrate/*.rb| | + + +## Rails/Output + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for the use of output calls like puts and print + +### Important attributes + +Attribute | Value | +--- | --- | +Include | app/**/*.rb, config/**/*.rb, db/**/*.rb, lib/**/*.rb| | + + +## Rails/OutputSafety + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for the use of output safety calls like html_safe and +raw. + +### Example + +```ruby +# bad +"

#{text}

".html_safe + +# good +content_tag(:p, text) + +# bad +out = "" +out << content_tag(:li, "one") +out << content_tag(:li, "two") +out.html_safe + +# good +out = [] +out << content_tag(:li, "one") +out << content_tag(:li, "two") +safe_join(out) +``` + +## Rails/PluralizationGrammar + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for correct grammar when using ActiveSupport's +core extensions to the numeric classes. + +### Example + +```ruby +# bad +3.day.ago +1.months.ago + +# good +3.days.ago +1.month.ago +``` + +## Rails/ReadWriteAttribute + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for the use of the read_attribute or +write_attribute methods. + +### Example + +```ruby +# bad +x = read_attribute(:attr) +write_attribute(:attr, val) + +# good +x = self[:attr] +self[:attr] = val +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Include | app/models/**/*.rb| | + + +## Rails/RequestReferer + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for consistent uses of request.referrer or +request.referrer, depending on configuration. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | referer| | +SupportedStyles | referer, referrer| | + + +## Rails/SafeNavigation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop transforms usages of a method call safeguarded by a non `nil` +check for the variable whose method is being called to +safe navigation (`&.`). + +Configuration option: ConvertCodeThatCanStartToReturnNil +The default for this is `false`. When configured to `true`, this will +check for code in the format `!foo.nil? && foo.bar`. As it is written, +the return of this code is limited to `false` and whatever the return +of the method is. If this is converted to safe navigation, +`foo&.bar` can start returning `nil` as well as what the method +returns. + +### Example + +```ruby +# bad +foo.bar if foo +foo.bar(param1, param2) if foo +foo.bar { |e| e.something } if foo +foo.bar(param) { |e| e.something } if foo + +foo.bar if !foo.nil? +foo.bar unless !foo +foo.bar unless foo.nil? + +foo && foo.bar +foo && foo.bar(param1, param2) +foo && foo.bar { |e| e.something } +foo && foo.bar(param) { |e| e.something } + +# good +foo&.bar +foo&.bar(param1, param2) +foo&.bar { |e| e.something } +foo&.bar(param) { |e| e.something } + +foo.nil? || foo.bar +!foo || foo.bar + +# Methods that `nil` will `respond_to?` should not be converted to +# use safe navigation +foo.to_i if foo +``` + +### Important attributes + +Attribute | Value | +--- | --- | +ConvertTry | false| | + + +## Rails/SaveBang + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop identifies possible cases where Active Record save! or related +should be used instead of save because the model might have failed to +save and an exception is better than unhandled failure. + +This will ignore calls that return a boolean for success if the result +is assigned to a variable or used as the condition in an if/unless +statement. It will also ignore calls that return a model assigned to a +variable that has a call to `persisted?`. Finally, it will ignore any +call with more than 2 arguments as that is likely not an Active Record +call or a Model.update(id, attributes) call. + +### Example + +```ruby +# bad +user.save +user.update(name: 'Joe') +user.find_or_create_by(name: 'Joe') +user.destroy + +# good +unless user.save + . . . +end +user.save! +user.update!(name: 'Joe') +user.find_or_create_by!(name: 'Joe') +user.destroy! + +user = User.find_or_create_by(name: 'Joe') +unless user.persisted? + . . . +end +``` + +## Rails/ScopeArgs + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for scope calls where it was passed +a method (usually a scope) instead of a lambda/proc. + +### Example + +```ruby +# bad +scope :something, where(something: true) + +# good +scope :something, -> { where(something: true) } +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Include | app/models/**/*.rb| | + + +## Rails/TimeZone + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for the use of Time methods without zone. + +Built on top of Ruby on Rails style guide (https://github.com/bbatsov/rails-style-guide#time) +and the article http://danilenko.org/2012/7/6/rails_timezones/ . + +Two styles are supported for this cop. When EnforcedStyle is 'strict' +then only use of Time.zone is allowed. + +When EnforcedStyle is 'flexible' then it's also allowed +to use Time.in_time_zone. + +### Example + +```ruby +# always offense +Time.now +Time.parse('2015-03-02 19:05:37') + +# no offense +Time.zone.now +Time.zone.parse('2015-03-02 19:05:37') + +# no offense only if style is 'acceptable' +Time.current +DateTime.strptime(str, "%Y-%m-%d %H:%M %Z").in_time_zone +Time.at(timestamp).in_time_zone +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | http://danilenko.org/2012/7/6/rails_timezones| | +EnforcedStyle | flexible| | +SupportedStyles | strict, flexible| | + + +## Rails/UniqBeforePluck + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Prefer the use of uniq (or distinct), before pluck instead of after. + +The use of uniq before pluck is preferred because it executes within +the database. + +This cop has two different enforcement modes. When the EnforcedMode +is conservative (the default) then only calls to pluck on a constant +(i.e. a model class) before uniq are added as offenses. + +When the EnforcedMode is aggressive then all calls to pluck before +uniq are added as offenses. This may lead to false positives as the cop +cannot distinguish between calls to pluck on an ActiveRecord::Relation +vs a call to pluck on an ActiveRecord::Associations::CollectionProxy. + +Autocorrect is disabled by default for this cop since it may generate +false positives. + +### Example + +```ruby +# bad +Model.pluck(:id).uniq + +# good +Model.uniq.pluck(:id) +``` +```ruby +# this will return a Relation that pluck is called on +Model.where(...).pluck(:id).uniq + +# an association on an instance will return a CollectionProxy +instance.assoc.pluck(:id).uniq +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedMode | conservative| | +SupportedModes | conservative, aggressive| | +AutoCorrect | false| | + + +## Rails/Validation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for the use of old-style attribute validation macros. + +### Important attributes + +Attribute | Value | +--- | --- | +Include | app/models/**/*.rb| | + diff --git a/manual/cops_security.md b/manual/cops_security.md new file mode 100644 index 000000000000..eccada8e6e5d --- /dev/null +++ b/manual/cops_security.md @@ -0,0 +1,37 @@ +# Security + +## Security/JSONLoad + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for the use of JSON class methods which have potential +security issues. + +Autocorrect is disabled by default because it's potentially dangerous. +If using a stream, like `JSON.load(open('file'))`, it will need to call +`#read` manually, like `JSON.parse(open('file').read)`. +If reading single values (rather than proper JSON objects), like +`JSON.load('false')`, it will need to pass the `quirks_mode: true` +option, like `JSON.parse('false', quirks_mode: true)`. +Other similar issues may apply. + +### Example + +```ruby +# always offense +JSON.load("{}") +JSON.restore("{}") + +# no offense +JSON.parse("{}") +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | http://ruby-doc.org/stdlib-2.3.0/libdoc/json/rdoc/JSON.html#method-i-load| | +AutoCorrect | false| | + diff --git a/manual/cops_style.md b/manual/cops_style.md new file mode 100644 index 000000000000..701be553d968 --- /dev/null +++ b/manual/cops_style.md @@ -0,0 +1,4792 @@ +# Style + +## Style/AccessModifierIndentation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Modifiers should be indented as deep as method definitions, or as deep +as the class/module keyword, depending on configuration. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | indent| | +SupportedStyles | outdent, indent| | +IndentationWidth | | | + + +## Style/AccessorMethodName + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop makes sure that accessor methods are named properly. + +### Example + +```ruby +# bad +def set_attribute(value) ... + +# good +def attribute=(value) + +# bad +def get_attribute ... + +# good +def attribute ... +``` + +## Style/Alias + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop finds uses of `alias` where `alias_method` would be more +appropriate (or is simply preferred due to configuration), and vice +versa. +It also finds uses of `alias :symbol` rather than `alias bareword`. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | prefer_alias| | +SupportedStyles | prefer_alias, prefer_alias_method| | + + +## Style/AlignArray + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Here we check if the elements of a multi-line array literal are +aligned. + +## Style/AlignHash + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Here we check if the keys, separators, and values of a multi-line hash +literal are aligned. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedHashRocketStyle | key| | +EnforcedColonStyle | key| | +EnforcedLastArgumentHashStyle | always_inspect| | +SupportedLastArgumentHashStyles | always_inspect, always_ignore, ignore_implicit, ignore_explicit| | + + +## Style/AlignParameters + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Here we check if the parameters on a multi-line method call or +definition are aligned. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | with_first_parameter| | +SupportedStyles | with_first_parameter, with_fixed_indentation| | +IndentationWidth | | | + + +## Style/AndOr + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for uses of *and* and *or*. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | always| | +SupportedStyles | always, conditionals| | + + +## Style/ArrayJoin + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for uses of "*" as a substitute for *join*. + +Not all cases can reliably checked, due to Ruby's dynamic +types, so we consider only cases when the first argument is an +array literal or the second is a string literal. + +## Style/AsciiComments + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for non-ascii (non-English) characters +in comments. + +## Style/AsciiIdentifiers + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for non-ascii characters in identifier names. + +## Style/Attr + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for uses of Module#attr. + +## Style/AutoResourceCleanup + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for cases when you could use a block +accepting version of a method that does automatic +resource cleanup. + +### Example + +```ruby +# bad +f = File.open('file') + +# good +f = File.open('file') do + ... +end +``` + +## Style/BarePercentLiterals + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks if usage of %() or %Q() matches configuration. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | bare_percent| | +SupportedStyles | percent_q, bare_percent| | + + +## Style/BeginBlock + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for BEGIN blocks. + +## Style/BlockComments + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop looks for uses of block comments (=begin...=end). + +## Style/BlockDelimiters + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Check for uses of braces or do/end around single line or +multi-line blocks. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | line_count_based| | +SupportedStyles | line_count_based, semantic, braces_for_chaining| | +ProceduralMethods | benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object| | +FunctionalMethods | let, let!, subject, watch| | +IgnoredMethods | lambda, proc, it| | + + +## Style/BlockEndNewline + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks whether the end statement of a do..end block +is on its own line. + +### Example + +```ruby +# 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 + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for braces around the last parameter in a method call +if the last parameter is a hash. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | no_braces| | +SupportedStyles | braces, no_braces, context_dependent| | + + +## Style/CaseEquality + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for uses of the case equality operator(===). + +## Style/CaseIndentation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks how the *when*s of a *case* expression +are indented in relation to its *case* or *end* keyword. + +It will register a separate offense for each misaligned *when*. + +### Important attributes + +Attribute | Value | +--- | --- | +IndentWhenRelativeTo | case| | +SupportedStyles | case, end| | +IndentOneStep | false| | +IndentationWidth | | | + + +## Style/CharacterLiteral + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for uses of the character literal ?x. + +## Style/ClassAndModuleCamelCase + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cops checks for class and module names with +an underscore in them. + +## Style/ClassAndModuleChildren + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks the style of children definitions at classes and +modules. Basically there are two different styles: + +nested - have each child on its own line + class Foo + class Bar + end + end + +compact - combine definitions as much as possible + class Foo::Bar + end + +The compact style is only forced for classes/modules with one child. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | nested| | +SupportedStyles | nested, compact| | + + +## Style/ClassCheck + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop enforces consistent use of `Object#is_a?` or `Object#kind_of?`. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | is_a?| | +SupportedStyles | is_a?, kind_of?| | + + +## Style/ClassMethods + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for uses of the class/module name instead of +self, when defining class/module methods. + +### Example + +```ruby +# bad +class SomeClass + def SomeClass.class_method + ... + end +end + +# good +class SomeClass + def self.class_method + ... + end +end +``` + +## Style/ClassVars + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for uses of class variables. Offenses +are signaled only on assignment to class variables to +reduced the number of offenses that would be reported. + +## Style/ClosingParenthesisIndentation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cops checks the indentation of hanging closing parentheses in +method calls, method definitions, and grouped expressions. A hanging +closing parenthesis means `)` preceded by a line break. + +### Example + +```ruby +# 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/CollectionMethods + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop enforces the use of consistent method names +from the Enumerable module. + +Unfortunately we cannot actually know if a method is from +Enumerable or not (static analysis limitation), so this cop +can yield some false positives. + +### Important attributes + +Attribute | Value | +--- | --- | +PreferredMethods | {"collect"=>"map", "collect!"=>"map!", "inject"=>"reduce", "detect"=>"find", "find_all"=>"select"}| | + + +## Style/ColonMethodCall + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for methods invoked via the :: operator instead +of the . operator (like FileUtils::rmdir instead of FileUtils.rmdir). + +## Style/CommandLiteral + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop enforces using `` or %x around command literals. + +### Example + +```ruby +# Good if EnforcedStyle is backticks or mixed, bad if percent_x. +folders = `find . -type d`.split + +# Good if EnforcedStyle is percent_x, bad if backticks or mixed. +folders = %x(find . -type d).split + +# Good if EnforcedStyle is backticks, bad if percent_x or mixed. +` + ln -s foo.example.yml foo.example + ln -s bar.example.yml bar.example +` + +# Good if EnforcedStyle is percent_x or mixed, bad if backticks. +%x( + ln -s foo.example.yml foo.example + ln -s bar.example.yml bar.example +) + +# Bad unless AllowInnerBackticks is true. +`echo \`ls\`` +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | backticks| | +SupportedStyles | backticks, percent_x, mixed| | +AllowInnerBackticks | false| | + + +## Style/CommentAnnotation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks that comment annotation keywords are written according +to guidelines. + +### Important attributes + +Attribute | Value | +--- | --- | +Keywords | TODO, FIXME, OPTIMIZE, HACK, REVIEW| | + + +## Style/CommentIndentation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cops checks the indentation of comments. + +## Style/ConditionalAssignment + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Check for `if` and `case` statements where each branch is used for +assignment to the same variable when using the return of the +condition can be used instead. + +### Example + +```ruby +EnforcedStyle: assign_to_condition + +# 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 + +EnforcedStyle: assign_inside_condition +# bad +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 + +# good +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 +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | assign_to_condition| | +SupportedStyles | assign_to_condition, assign_inside_condition| | +SingleLineConditionsOnly | true| | + + +## Style/ConstantName + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks whether constant names are written using +SCREAMING_SNAKE_CASE. + +To avoid false positives, it ignores cases in which we cannot know +for certain the type of value that would be assigned to a constant. + +## Style/Copyright + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Check that a copyright notice was given in each source file. + +The default regexp for an acceptable copyright notice can be found in +config/default.yml. The default can be changed as follows: + +Style/Copyright: + Notice: '^Copyright (\(c\) )?2\d{3} Acme Inc' + +This regex string is treated as an unanchored regex. For each file +that RuboCop scans, a comment that matches this regex must be found or +an offense is reported. + +### Important attributes + +Attribute | Value | +--- | --- | +Notice | ^Copyright (\(c\) )?2[0-9]{3} .+| | +AutocorrectNotice | | | + + +## Style/DefWithParentheses + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for parentheses in the definition of a method, +that does not take any arguments. Both instance and +class/singleton methods are checked. + +## Style/Documentation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for missing top-level documentation of +classes and modules. Classes with no body are exempt from the +check and so are namespace modules - modules that have nothing in +their bodies except classes, other modules, or constant definitions. + +The documentation requirement is annulled if the class or module has +a "#:nodoc:" comment next to it. Likewise, "#:nodoc: all" does the +same for all its children. + +### Important attributes + +Attribute | Value | +--- | --- | +Exclude | /spec/**/*, /test/**/*| | + + +## Style/DocumentationMethod + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for missing documentation comment for public methods. +It can optionally be configured to also require documentation for +non-public methods. + +### Example + +```ruby +# bad + +class Foo + def bar + puts baz + end +end + +module Foo + def bar + puts baz + end +end + +def foo.bar + puts baz +end + +# good + +class Foo + # Documentation + def bar + puts baz + end +end + +module Foo + # Documentation + def bar + puts baz + end +end + +# Documenation +def foo.bar + puts baz +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Exclude | /spec/**/*, /test/**/*| | +RequireForNonPublicMethods | false| | + + +## Style/DotPosition + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks the . position in multi-line method calls. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | leading| | +SupportedStyles | leading, trailing| | + + +## Style/DoubleNegation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for uses of double negation (!!) to convert something +to a boolean value. As this is both cryptic and usually redundant, it +should be avoided. + +Please, note that when something is a boolean value +!!something and !something.nil? are not the same thing. +As you're unlikely to write code that can accept values of any type +this is rarely a problem in practice. + +### Example + +```ruby +# bad +!!something + +# good +!something.nil? +``` + +## Style/EachForSimpleLoop + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for loops which iterate a constant number of times, +using a Range literal and `#each`. This can be done more readably using +`Integer#times`. + +This check only applies if the block takes no parameters. + +### Example + +```ruby +# bad +(1..5).each { } + +# good +5.times { } +``` +```ruby +# bad +(0...10).each {} + +# good +10.times {} +``` + +## Style/EachWithObject + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop looks for inject / reduce calls where the passed in object is +returned at the end and so could be replaced by each_with_object without +the need to return the object at the end. + +However, we can't replace with each_with_object if the accumulator +parameter is assigned to within the block. + +### Example + +```ruby +# bad +[1, 2].inject({}) { |a, e| a[e] = e; a } + +# good +[1, 2].each_with_object({}) { |e, a| a[e] = e } +``` + +## Style/ElseAlignment + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cops checks the alignment of else keywords. Normally they should +be aligned with an if/unless/while/until/begin/def keyword, but there +are special cases when they should follow the same rules as the +alignment of end. + +## Style/EmptyCaseCondition + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for case statements with an empty condition. + +### Example + +```ruby +# bad: +case +when x == 0 + puts 'x is 0' +when y == 0 + puts 'y is 0' +else + puts 'neither is 0' +end + +# good: +if x == 0 + puts 'x is 0' +elsif y == 0 + puts 'y is 0' +else + puts 'neither is 0' +end + +# good: (the case condition node is not empty) +case n +when 0 + puts 'zero' +when 1 + puts 'one' +else + puts 'more' +end +``` + +## Style/EmptyElse + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks for empty else-clauses, possibly including comments and/or an +explicit `nil` depending on the EnforcedStyle. + +SupportedStyles: + +### Example + +```ruby +# good for all styles + +if condition + statement +else + statement +end + +# good for all styles +if condition + statement +end +``` +```ruby +# empty - warn only on empty else + +# bad +if condition + statement +else +end + +# good +if condition + statement +else + nil +end +``` +```ruby +# nil - warn on else with nil in it + +# bad +if condition + statement +else + nil +end + +# good +if condition + statement +else +end +``` +```ruby +# both - warn on empty else and else with nil in it + +# bad +if condition + statement +else + nil +end + +# bad +if condition + statement +else +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | both| | +SupportedStyles | empty, nil, both| | + + +## Style/EmptyLineBetweenDefs + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks whether method definitions are +separated by empty lines. + +### Important attributes + +Attribute | Value | +--- | --- | +AllowAdjacentOneLineDefs | false| | + + +## Style/EmptyLines + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cops checks for two or more consecutive blank lines. + +## Style/EmptyLinesAroundAccessModifier + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Access modifiers should be surrounded by blank lines. + +## Style/EmptyLinesAroundBlockBody + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cops checks if empty lines around the bodies of blocks match +the configuration. + +### Example + +```ruby +# EnforcedStyle: empty_lines + +# good + +foo do |bar| + + ... + +end + +# EnforcedStyle: no_empty_lines + +# good + +foo do |bar| + ... +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | no_empty_lines| | +SupportedStyles | empty_lines, no_empty_lines| | + + +## Style/EmptyLinesAroundClassBody + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cops checks if empty lines around the bodies of classes match +the configuration. + +### Example + +```ruby +EnforcedStyle: empty_lines + +# good + +class Foo + + def bar + ... + end + +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | no_empty_lines| | +SupportedStyles | empty_lines, empty_lines_except_namespace, no_empty_lines| | + + +## Style/EmptyLinesAroundMethodBody + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cops checks if empty lines exist around the bodies of methods. + +### Example + +```ruby +# good + +def foo + ... +end + +# bad + +def bar + + ... + +end +``` + +## Style/EmptyLinesAroundModuleBody + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cops checks if empty lines around the bodies of modules match +the configuration. + +### Example + +```ruby +EnforcedStyle: empty_lines + +# good + +module Foo + + def bar + ... + end + +end + +EnforcedStyle: no_empty_lines + +# good + +module Foo + def bar + ... + end +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | no_empty_lines| | +SupportedStyles | empty_lines, empty_lines_except_namespace, no_empty_lines| | + + +## Style/EmptyLiteral + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for the use of a method, the result of which +would be a literal, like an empty array, hash or string. + +## Style/Encoding + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks whether the source file has a utf-8 encoding +comment or not. +Setting this check to "always" and "when_needed" makes sense only +for code that should support Ruby 1.9, since in 2.0+ utf-8 is the +default source file encoding. There are three styles: + +when_needed - only enforce an encoding comment if there are non ASCII + characters, otherwise report an offense +always - enforce encoding comment in all files +never - enforce no encoding comment in all files + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | when_needed| | +SupportedStyles | when_needed, always, never| | +AutoCorrectEncodingComment | # encoding: utf-8| | + + +## Style/EndBlock + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for END blocks. + +## Style/EndOfLine + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for Windows-style line endings in the source code. + +## Style/EvenOdd + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for places where Integer#even? or Integer#odd? +should have been used. + +### Example + +```ruby +# bad +if x % 2 == 0 + +# good +if x.even? +``` + +## Style/ExtraSpacing + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for extra/unnecessary whitespace. + +### Example + +```ruby +# 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" +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AllowForAlignment | true| | +ForceEqualSignAlignment | false| | + + +## Style/FileName + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop makes sure that Ruby source files have snake_case +names. Ruby scripts (i.e. source files with a shebang in the +first line) are ignored. + +### Important attributes + +Attribute | Value | +--- | --- | +Exclude | | | +ExpectMatchingDefinition | false| | +Regex | | | +IgnoreExecutableScripts | true| | + + +## Style/FirstArrayElementLineBreak + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for a line break before the first element in a +multi-line array. + +### Example + +```ruby +# bad +[ :a, + :b] + +# good +[ + :a, + :b] +``` + +## Style/FirstHashElementLineBreak + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for a line break before the first element in a +multi-line hash. + +### Example + +```ruby +# bad +{ a: 1, + b: 2} + +# good +{ + a: 1, + b: 2 } +``` + +## Style/FirstMethodArgumentLineBreak + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for a line break before the first argument in a +multi-line method call. + +### Example + +```ruby +# bad +method(foo, bar, + baz) + +# good +method( + foo, bar, + baz) + +# ignored +method foo, bar, + baz +``` + +## Style/FirstMethodParameterLineBreak + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for a line break before the first parameter in a +multi-line method parameter definition. + +### Example + +```ruby +# bad +def method(foo, bar, + baz) + do_something +end + +# good +def method( + foo, bar, + baz) + do_something +end + +# ignored +def method foo, + bar + do_something +end +``` + +## Style/FirstParameterIndentation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks the indentation of the first parameter in a method call. +Parameters after the first one are checked by Style/AlignParameters, not +by this cop. + +### Example + +```ruby +# bad +some_method( +first_param, +second_param) + +# good +some_method( + first_param, +second_param) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | special_for_inner_method_call_in_parentheses| | +SupportedStyles | consistent, special_for_inner_method_call, special_for_inner_method_call_in_parentheses| | +IndentationWidth | | | + + +## Style/FlipFlop + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop looks for uses of flip flop operator + +## Style/For + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop looks for uses of the *for* keyword, or *each* method. The +preferred alternative is set in the EnforcedStyle configuration +parameter. An *each* call with a block on a single line is always +allowed, however. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | each| | +SupportedStyles | for, each| | + + +## Style/FormatString + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop enforces the use of a single string formatting utility. +Valid options include Kernel#format, Kernel#sprintf and String#%. + +The detection of String#% cannot be implemented in a reliable +manner for all cases, so only two scenarios are considered - +if the first argument is a string literal and if the second +argument is an array literal. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | format| | +SupportedStyles | format, sprintf, percent| | + + +## Style/FrozenStringLiteralComment + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop is designed to help upgrade to Ruby 3.0. It will add the +comment `# frozen_string_literal: true` to the top of files to +enable frozen string literals. Frozen string literals will be default +in Ruby 3.0. The comment will be added below a shebang and encoding +comment. The frozen string literal comment is only valid in Ruby 2.3+. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | always| | +SupportedStyles | when_needed, always| | + + +## Style/GlobalVars + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cops looks for uses of global variables. +It does not report offenses for built-in global variables. +Built-in global variables are allowed by default. Additionally +users can allow additional variables via the AllowedVariables option. + +Note that backreferences like $1, $2, etc are not global variables. + +### Important attributes + +Attribute | Value | +--- | --- | +Reference | http://www.zenspider.com/Languages/Ruby/QuickRef.html| | +AllowedVariables | | | + + +## Style/GuardClause + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +Use a guard clause instead of wrapping the code inside a conditional +expression + +### Example + +```ruby +# 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 +``` + +### Important attributes + +Attribute | Value | +--- | --- | +MinBodyLength | 1| | + + +## Style/HashSyntax + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks hash literal syntax. + +It can enforce either the use of the class hash rocket syntax or +the use of the newer Ruby 1.9 syntax (when applicable). + +A separate offense is registered for each problematic pair. + +The supported styles are: + +* ruby19 - forces use of the 1.9 syntax (e.g. {a: 1}) when hashes have + all symbols for keys +* hash_rockets - forces use of hash rockets for all hashes +* no_mixed_keys - simply checks for hashes with mixed syntaxes +* ruby19_mixed_keys - forces use of ruby 1.9 syntax and forbids mixed + syntax hashes + +### Example + +```ruby +"EnforcedStyle => 'ruby19'" + +# good +{a: 2, b: 1} +{:c => 2, 'd' => 2} # acceptable since 'd' isn't a symbol +{d: 1, 'e' => 2} # technically not forbidden + +# bad +{:a => 2} +{b: 1, :c => 2} +``` +```ruby +"EnforcedStyle => 'hash_rockets'" + +# good +{:a => 1, :b => 2} + +# bad +{a: 1, b: 2} +{c: 1, 'd' => 5} +``` +```ruby +"EnforcedStyle => 'no_mixed_keys'" + +# good +{:a => 1, :b => 2} +{c: 1, d: 2} + +# bad +{:a => 1, b: 2} +{c: 1, 'd' => 2} +``` +```ruby +"EnforcedStyle => 'ruby19_no_mixed_keys'" + +# good +{a: 1, b: 2} +{:c => 3, 'd' => 4} + +# bad +{:a => 1, :b => 2} +{c: 2, 'd' => 3} # should just use hash rockets +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | ruby19| | +SupportedStyles | ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys| | +UseHashRocketsWithSymbolValues | false| | +PreferHashRocketsForNonAlnumEndingSymbols | false| | + + +## Style/IdenticalConditionalBranches + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for identical lines at the end of each branch of a +conditional statement. + +### Example + +```ruby +# bad +if condition + do_x + do_z +else + do_y + do_z +end + +# good +if condition + do_x +else + do_y +end +do_z +``` + +## Style/IfInsideElse + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +If the `else` branch of a conditional consists solely of an `if` node, +it can be combined with the `else` to become an `elsif`. +This helps to keep the nesting level from getting too deep. + +### Example + +```ruby +# good +if condition_a + action_a +elsif condition_b + action_b +else + action_c +end + +# bad +if condition_a + action_a +else + if condition_b + action_b + else + action_c + end +end +``` + +## Style/IfUnlessModifier + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks for if and unless statements that would fit on one line +if written as a modifier if/unless. +The maximum line length is configurable. + +### Important attributes + +Attribute | Value | +--- | --- | +MaxLineLength | 80| | + + +## Style/IfUnlessModifierOfIfUnless + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +Checks for if and unless statements used as modifers of other if or +unless statements. + +### Example + +```ruby +# bad +tired? ? 'stop' : 'go faster' if running? + +# bad +if tired? + "please stop" +else + "keep going" +end if running? + +# good +if running? + tired? ? 'stop' : 'go faster' +end +``` + +## Style/IfWithSemicolon + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +Checks for uses of semicolon in if statements. + +## Style/ImplicitRuntimeError + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for `raise` or `fail` statements which do not specify an +explicit exception class. (This raises a `RuntimeError`. Some projects +might prefer to use exception classes which more precisely identify the +nature of the error.) + +### Example + +```ruby +# bad +raise 'Error message here' + +# good +raise ArgumentError, 'Error message here' +``` + +## Style/IndentArray + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks the indentation of the first element in an array literal +where the opening bracket and the first element are on separate lines. +The other elements' indentations are handled by the AlignArray cop. + +By default, array literals that are arguments in a method call with +parentheses, and where the opening square bracket of the array is on the +same line as the opening parenthesis of the method call, shall have +their first element indented one step (two spaces) more than the +position inside the opening parenthesis. + +Other array literals shall have their first element indented one step +more than the start of the line where the opening square bracket is. + +This default style is called 'special_inside_parentheses'. Alternative +styles are 'consistent' and 'align_brackets'. Here are examples: + + # special_inside_parentheses + array = [ + :value + ] + but_in_a_method_call([ + :its_like_this + ]) + # consistent + array = [ + :value + ] + and_in_a_method_call([ + :no_difference + ]) + # align_brackets + and_now_for_something = [ + :completely_different + ] + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | special_inside_parentheses| | +SupportedStyles | special_inside_parentheses, consistent, align_brackets| | +IndentationWidth | | | + + +## Style/IndentAssignment + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks the indentation of the first line of the +right-hand-side of a multi-line assignment. + +The indentation of the remaining lines can be corrected with +other cops such as `IndentationConsistency` and `EndAlignment`. + +### Example + +```ruby +# bad +value = +if foo + 'bar' +end + +# good +value = + if foo + 'bar' +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +IndentationWidth | | | + + +## Style/IndentHash + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cops checks the indentation of the first key in a hash literal +where the opening brace and the first key are on separate lines. The +other keys' indentations are handled by the AlignHash cop. + +By default, Hash literals that are arguments in a method call with +parentheses, and where the opening curly brace of the hash is on the +same line as the opening parenthesis of the method call, shall have +their first key indented one step (two spaces) more than the position +inside the opening parenthesis. + +Other hash literals shall have their first key indented one step more +than the start of the line where the opening curly brace is. + +This default style is called 'special_inside_parentheses'. Alternative +styles are 'consistent' and 'align_braces'. Here are examples: + + # special_inside_parentheses + hash = { + key: :value + } + but_in_a_method_call({ + its_like: :this + }) + # consistent + hash = { + key: :value + } + and_in_a_method_call({ + no: :difference + }) + # align_braces + and_now_for_something = { + completely: :different + } + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | special_inside_parentheses| | +SupportedStyles | special_inside_parentheses, consistent, align_braces| | +IndentationWidth | | | + + +## Style/IndentationConsistency + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cops checks for inconsistent indentation. + +### Example + +```ruby +class A + def test + puts 'hello' + puts 'world' + end +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | normal| | +SupportedStyles | normal, rails| | + + +## Style/IndentationWidth + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cops checks for indentation that doesn't use two spaces. + +### Example + +```ruby +class A + def test + puts 'hello' + end +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +Width | 2| | + + +## Style/InfiniteLoop + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Use `Kernel#loop` for infinite loops. + +### Example + +```ruby +# bad +while true + work +end + +# good +loop do + work +end +``` + +## Style/InitialIndentation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cops checks for indentation of the first non-blank non-comment +line in a file. + +## Style/InlineComment + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for trailing inline comments. + +### Example + +```ruby +# good +foo.each do |f| + # Standalone comment + f.bar +end + +# bad +foo.each do |f| + f.bar # Trailing inline comment +end +``` + +## Style/Lambda + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop (by default) checks for uses of the lambda literal syntax for +single line lambdas, and the method call syntax for multiline lambdas. +It is configurable to enforce one of the styles for both single line +and multiline lambdas as well. + +### Example + +```ruby +# EnforcedStyle: line_count_dependent (default) + +# bad +f = lambda { |x| x } +f = ->(x) do + x + end + +# good +f = ->(x) { x } +f = lambda do |x| + x + end +``` +```ruby +# EnforcedStyle: lambda + +# bad +f = ->(x) { x } +f = ->(x) do + x + end + +# good +f = lambda { |x| x } +f = lambda do |x| + x + end +``` +```ruby +# EnforcedStyle: literal + +# bad +f = lambda { |x| x } +f = lambda do |x| + x + end + +# good +f = ->(x) { x } +f = ->(x) do + x + end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | line_count_dependent| | +SupportedStyles | line_count_dependent, lambda, literal| | + + +## Style/LambdaCall + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for use of the lambda.(args) syntax. + +### Example + +```ruby +# bad +lambda.(x, y) + +# good +lambda.call(x, y) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | call| | +SupportedStyles | call, braces| | + + +## Style/LeadingCommentSpace + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks whether comments have a leading space +after the # denoting the start of the comment. The +leading space is not required for some RDoc special syntax, +like #++, #--, #:nodoc, etc. Neither is it required for +=begin/=end comments. + +## Style/LineEndConcatenation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for string literal concatenation at +the end of a line. + +### Example + +```ruby +# bad +some_str = 'ala' + + 'bala' + +some_str = 'ala' << + 'bala' + +# good +some_str = 'ala' \ + 'bala' +``` + +## Style/MethodCallParentheses + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for unwanted parentheses in parameterless method calls. + +## Style/MethodCalledOnDoEndBlock + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for methods called on a do...end block. The point of +this check is that it's easy to miss the call tacked on to the block +when reading code. + +### Example + +```ruby +a do + b +end.c +``` + +## Style/MethodDefParentheses + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cops checks for parentheses around the arguments in method +definitions. Both instance and class/singleton methods are checked. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | require_parentheses| | +SupportedStyles | require_parentheses, require_no_parentheses, require_no_parentheses_except_multiline| | + + +## Style/MethodMissing + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for the presence of `method_missing` without also +defining `respond_to_missing?` and falling back on `super`. + +### Example + +```ruby +#bad +def method_missing(...) + ... +end + +#good +def respond_to_missing?(...) + ... +end + +def method_missing(...) + ... + super +end +``` + +## Style/MethodName + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop makes sure that all methods use the configured style, +snake_case or camelCase, for their names. Some special arrangements +have to be made for operator methods. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | snake_case| | +SupportedStyles | snake_case, camelCase| | + + +## Style/MissingElse + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +Checks for `if` expressions that do not have an `else` branch. +SupportedStyles + +if +case + +### Example + +```ruby +# bad +if condition + statement +end +``` +```ruby +# bad +case var +when condition + statement +end +``` +```ruby +# good +if condition + statement +else +# the content of the else branch will be determined by Style/EmptyElse +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | both| | +SupportedStyles | if, case, both| | + + +## Style/ModuleFunction + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cops checks for use of `extend self` or `module_function` in a +module. + +Supported styles are: module_function, extend_self. + +These offenses are not auto-corrected since there are different +implications to each approach. + +### Example + +```ruby +# Good if EnforcedStyle is module_function +module Test + module_function + ... +end + +# Good if EnforcedStyle is extend_self +module Test + extend self + ... +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | module_function| | +SupportedStyles | module_function, extend_self| | + + +## Style/MultilineArrayBraceLayout + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks that the closing brace in an array literal is either +on the same line as the last array element, or a new line. + +When using the `symmetrical` (default) style: + +If an array's opening brace is on the same line as the first element +of the array, then the closing brace should be on the same line as +the last element of the array. + +If an array's opening brace is on the line above the first element +of the array, then the closing brace should be on the line below +the last element of the array. + +When using the `new_line` style: + +The closing brace of a multi-line array literal must be on the line +after the last element of the array. + +When using the `same_line` style: + +The closing brace of a multi-line array literal must be on the same +line as the last element of the array. + +### Example + +```ruby +# symmetrical: bad +# new_line: good +# same_line: bad +[ :a, + :b +] + +# symmetrical: bad +# new_line: bad +# same_line: good +[ + :a, + :b ] + +# symmetrical: good +# new_line: bad +# same_line: good +[ :a, + :b ] + +# symmetrical: good +# new_line: good +# same_line: bad +[ + :a, + :b +] +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | symmetrical| | +SupportedStyles | symmetrical, new_line, same_line| | + + +## Style/MultilineAssignmentLayout + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks whether the multiline assignments have a newline +after the assignment operator. + +### Example + +```ruby +# bad (with EnforcedStyle set to new_line) +foo = if expression + 'bar' +end + +# good (with EnforcedStyle set to same_line) +foo = if expression + 'bar' +end + +# good (with EnforcedStyle set to new_line) +foo = + if expression + 'bar' + end + +# good (with EnforcedStyle set to new_line) +foo = + begin + compute + rescue => e + nil + end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +SupportedTypes | block, case, class, if, kwbegin, module| | +EnforcedStyle | new_line| | +SupportedStyles | same_line, new_line| | + + +## Style/MultilineBlockChain + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for chaining of a block after another block that spans +multiple lines. + +### Example + +```ruby +Thread.list.find_all do |t| + t.alive? +end.map do |t| + t.object_id +end +``` + +## Style/MultilineBlockLayout + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks whether the multiline do end blocks have a newline +after the start of the block. Additionally, it checks whether the block +arguments, if any, are on the same line as the start of the block. + +### Example + +```ruby +# 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/MultilineHashBraceLayout + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks that the closing brace in a hash literal is either +on the same line as the last hash element, or a new line. + +When using the `symmetrical` (default) style: + +If a hash's opening brace is on the same line as the first element +of the hash, then the closing brace should be on the same line as +the last element of the hash. + +If a hash's opening brace is on the line above the first element +of the hash, then the closing brace should be on the line below +the last element of the hash. + +When using the `new_line` style: + +The closing brace of a multi-line hash literal must be on the line +after the last element of the hash. + +When using the `same_line` style: + +The closing brace of a multi-line hash literal must be on the same +line as the last element of the hash. + +### Example + +```ruby +# symmetrical: bad +# new_line: good +# same_line: bad +{ a: 1, + b: 2 +} + +# symmetrical: bad +# new_line: bad +# same_line: good +{ + a: 1, + b: 2 } + +# symmetrical: good +# new_line: bad +# same_line: good +{ a: 1, + b: 2 } + +# symmetrical: good +# new_line: good +# same_line: bad +{ + a: 1, + b: 2 +} +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | symmetrical| | +SupportedStyles | symmetrical, new_line, same_line| | + + +## Style/MultilineIfThen + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for uses of the `then` keyword in multi-line if statements. + +### Example + +```ruby +if cond then +end +``` +```ruby +if cond then a +elsif cond then b +end +``` + +## Style/MultilineMemoization + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks that multiline memoizations are wrapped in a `begin` +and `end` block. + +### Example + +```ruby +# bad +foo ||= ( + bar + baz +) + +# good +foo ||= begin + bar + baz +end +``` + +## Style/MultilineMethodCallBraceLayout + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks that the closing brace in a method call is either +on the same line as the last method argument, or a new line. + +When using the `symmetrical` (default) style: + +If a method call's opening brace is on the same line as the first +argument of the call, then the closing brace should be on the same +line as the last argument of the call. + +If an method call's opening brace is on the line above the first +argument of the call, then the closing brace should be on the line +below the last argument of the call. + +When using the `new_line` style: + +The closing brace of a multi-line method call must be on the line +after the last argument of the call. + +When using the `same_line` style: + +The closing brace of a multi-line method call must be on the same +line as the last argument of the call. + +### Example + +```ruby +# symmetrical: bad +# new_line: good +# same_line: bad +foo(a, + b +) + +# symmetrical: bad +# new_line: bad +# same_line: good +foo( + a, + b) + +# symmetrical: good +# new_line: bad +# same_line: good +foo(a, + b) + +# symmetrical: good +# new_line: good +# same_line: bad +foo( + a, + b +) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | symmetrical| | +SupportedStyles | symmetrical, new_line, same_line| | + + +## Style/MultilineMethodCallIndentation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks the indentation of the method name part in method calls +that span more than one line. + +### Example + +```ruby +# bad +while a +.b + something +end + +# good, EnforcedStyle: aligned +while a + .b + something +end + +# good, EnforcedStyle: aligned +Thing.a + .b + .c + +# good, EnforcedStyle: indented +while a + .b + something +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | aligned| | +SupportedStyles | aligned, indented, indented_relative_to_receiver| | +IndentationWidth | | | + + +## Style/MultilineMethodDefinitionBraceLayout + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks that the closing brace in a method definition is either +on the same line as the last method parameter, or a new line. + +When using the `symmetrical` (default) style: + +If a method definition's opening brace is on the same line as the +first parameter of the definition, then the closing brace should be +on the same line as the last parameter of the definition. + +If an method definition's opening brace is on the line above the first +parameter of the definition, then the closing brace should be on the +line below the last parameter of the definition. + +When using the `new_line` style: + +The closing brace of a multi-line method definition must be on the line +after the last parameter of the definition. + +When using the `same_line` style: + +The closing brace of a multi-line method definition must be on the same +line as the last parameter of the definition. + +### Example + +```ruby +# symmetrical: bad +# new_line: good +# same_line: bad +def foo(a, + b +) + +# symmetrical: bad +# new_line: bad +# same_line: good +def foo( + a, + b) + +# symmetrical: good +# new_line: bad +# same_line: good +def foo(a, + b) + +# symmetrical: good +# new_line: good +# same_line: bad +def foo( + a, + b +) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | symmetrical| | +SupportedStyles | symmetrical, new_line, same_line| | + + +## Style/MultilineOperationIndentation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks the indentation of the right hand side operand in +binary operations that span more than one line. + +### Example + +```ruby +# bad +if a + +b + something +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | aligned| | +SupportedStyles | aligned, indented| | +IndentationWidth | | | + + +## Style/MultilineTernaryOperator + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for multi-line ternary op expressions. + +## Style/MutableConstant + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks whether some constant value isn't a +mutable literal (e.g. array or hash). + +### Example + +```ruby +# bad +CONST = [1, 2, 3] + +# good +CONST = [1, 2, 3].freeze +``` + +## Style/NegatedIf + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for uses of if with a negated condition. Only ifs +without else are considered. + +## Style/NegatedWhile + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for uses of while with a negated condition. + +## Style/NestedModifier + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for nested use of if, unless, while and until in their +modifier form. + +### Example + +```ruby +# bad +something if a if b + +# good +something if b && a +``` + +## Style/NestedParenthesizedCalls + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for unparenthesized method calls in the argument list +of a parenthesized method call. + +### Example + +```ruby +# good +method1(method2(arg), method3(arg)) + +# bad +method1(method2 arg, method3, arg) +``` + +## Style/NestedTernaryOperator + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for nested ternary op expressions. + +## Style/Next + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Use `next` to skip iteration instead of a condition at the end. + +### Example + +```ruby +# bad +[1, 2].each do |a| + if a == 1 do + puts a + end +end + +# good +[1, 2].each do |a| + next unless a == 1 + puts a +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | skip_modifier_ifs| | +MinBodyLength | 3| | +SupportedStyles | skip_modifier_ifs, always| | + + +## Style/NilComparison + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for comparison of something with nil using ==. + +### Example + +```ruby +# bad +if x == nil + +# good +if x.nil? +``` + +## Style/NonNilCheck + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for non-nil checks, which are usually redundant. + +Non-nil checks are allowed if they are the final nodes of predicate. + + # good + def signed_in? + !current_user.nil? + end + +### Example + +```ruby +# bad +if x != nil + +# good (when not allowing semantic changes) +# bad (when allowing semantic changes) +if !x.nil? + +# good (when allowing semantic changes) +if x +``` + +### Important attributes + +Attribute | Value | +--- | --- | +IncludeSemanticChanges | false| | + + +## Style/Not + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for uses if the keyword *not* instead of !. + +## Style/NumericLiteralPrefix + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for octal, hex, binary and decimal literals using +uppercase prefixes and corrects them to lowercase prefix +or no prefix (in case of decimals). +eg. for octal use `0o` instead of `0` or `0O`. + +Can be configured to use `0` only for octal literals using +`EnforcedOctalStyle` => `zero_only` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedOctalStyle | zero_with_o| | +SupportedOctalStyles | zero_with_o, zero_only| | + + +## Style/NumericLiterals + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for big numeric literals without _ between groups +of digits in them. + +### Important attributes + +Attribute | Value | +--- | --- | +MinDigits | 5| | + + +## Style/NumericPredicate + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for usage of comparison operators (`==`, `!=`, +`>`, `<`) to test numbers as zero, nonzero, positive, or negative. +These can be replaced by their respective predicate methods. +The cop can also be configured to do the reverse. + +### Example + +```ruby +# EnforcedStyle: predicate (default) + +# bad + +foo == 0 +0 != bar.baz +0 > foo +bar.baz > 0 + +# good + +foo.zero? +bar.baz.nonzero? +foo.negative? +bar.baz.positive? +``` +```ruby +# EnforcedStyle: comparison + +# bad + +foo.zero? +bar.baz.nonzero? +foo.negative? +bar.baz.positive? + +# good + +foo == 0 +0 != bar.baz +0 > foo +bar.baz > 0 +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AutoCorrect | false| | +EnforcedStyle | predicate| | +SupportedStyles | predicate, comparison| | +Exclude | /spec/**/*| | + + +## Style/OneLineConditional + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +TODO: Make configurable. +Checks for uses of if/then/else/end on a single line. + +## Style/OpMethod + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop makes sure that certain binary operator methods have their +sole parameter named `other`. + +### Example + +```ruby +# bad +def +(amount); end + +# good +def +(other); end +``` + +## Style/OptionHash + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks for options hashes and discourages them if the +current Ruby version supports keyword arguments. + +### Example + +```ruby +Instead of: + +def fry(options = {}) + temperature = options.fetch(:temperature, 300) + ... +end + +Prefer: + +def fry(temperature: 300) + ... +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +SuspiciousParamNames | options, opts, args, params, parameters| | + + +## Style/OptionalArguments + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for optional arguments to methods +that do not come at the end of the argument list + +### Example + +```ruby +# bad +def foo(a = 1, b, c) +end + +# good +def baz(a, b, c = 1) +end + +def foobar(a = 1, b = 2, c = 3) +end +``` + +## Style/ParallelAssignment + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for simple usages of parallel assignment. +This will only complain when the number of variables +being assigned matched the number of assigning variables. + +### Example + +```ruby +# bad +a, b, c = 1, 2, 3 +a, b, c = [1, 2, 3] + +# good +one, two = *foo +a, b = foo() +a, b = b, a + +a = 1 +b = 2 +c = 3 +``` + +## Style/ParenthesesAroundCondition + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for the presence of superfluous parentheses around the +condition of if/unless/while/until. + +### Important attributes + +Attribute | Value | +--- | --- | +AllowSafeAssignment | true| | + + +## Style/PercentLiteralDelimiters + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop enforces the consistent usage of `%`-literal delimiters. + +### Important attributes + +Attribute | Value | +--- | --- | +PreferredDelimiters | {"%"=>"()", "%i"=>"()", "%I"=>"()", "%q"=>"()", "%Q"=>"()", "%r"=>"{}", "%s"=>"()", "%w"=>"()", "%W"=>"()", "%x"=>"()"}| | + + +## Style/PercentQLiterals + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for usage of the %Q() syntax when %q() would do. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | lower_case_q| | +SupportedStyles | lower_case_q, upper_case_q| | + + +## Style/PerlBackrefs + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop looks for uses of Perl-style regexp match +backreferences like $1, $2, etc. + +## Style/PredicateName + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop makes sure that predicates are named properly. + +### Example + +```ruby +# bad +def is_even?(value) ... + +# good +def even?(value) + +# bad +def has_value? ... + +# good +def value? ... +``` + +### Important attributes + +Attribute | Value | +--- | --- | +NamePrefix | is_, has_, have_| | +NamePrefixBlacklist | is_, has_, have_| | +NameWhitelist | is_a?| | +Exclude | /spec/**/*| | + + +## Style/PreferredHashMethods + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop (by default) checks for uses of methods Hash#has_key? and +Hash#has_value? where it enforces Hash#key? and Hash#value? +It is configurable to enforce the inverse, using `verbose` method +names also. + +### Example + +```ruby +# EnforcedStyle: short (default) + +# bad +Hash#has_key? +Hash#has_value? + +# good +Hash#key? +Hash#value? +``` +```ruby +# EnforcedStyle: verbose + +# bad +Hash#key? +Hash#value? + +# good +Hash#has_key? +Hash#has_value? +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | short| | +SupportedStyles | short, verbose| | + + +## Style/Proc + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cops checks for uses of Proc.new where Kernel#proc +would be more appropriate. + +## Style/RaiseArgs + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks the args passed to `fail` and `raise`. For exploded +style (default), it recommends passing the exception class and message +to `raise`, rather than construct an instance of the error. It will +still allow passing just a message, or the construction of an error +with more than one argument. + +The exploded style works identically, but with the addition that it +will also suggest constructing error objects when the exception is +passed multiple arguments. + +### Example + +```ruby +# EnforcedStyle: exploded + +# bad +raise StandardError.new("message") + +# good +raise StandardError, "message" +fail "message" +raise RuntimeError.new(arg1, arg2, arg3) +``` +```ruby +# EnforcedStyle: compact + +# bad +raise StandardError, "message" +raise RuntimeError, arg1, arg2, arg3 + +# good +raise StandardError.new("message") +raise RuntimeError.new(arg1, arg2, arg3) +fail "message" +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | exploded| | +SupportedStyles | compact, exploded| | + + +## Style/RedundantBegin + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for redundant `begin` blocks. + +Currently it checks for code like this: + +### Example + +```ruby +def redundant + begin + ala + bala + rescue StandardError => e + something + end +end + +def preferred + ala + bala +rescue StandardError => e + something +end +``` + +## Style/RedundantException + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for RuntimeError as the argument of raise/fail. + +It checks for code like this: + +### Example + +```ruby +# Bad +raise RuntimeError, 'message' + +# Bad +raise RuntimeError.new('message') + +# Good +raise 'message' +``` + +## Style/RedundantFreeze + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop check for uses of Object#freeze on immutable objects. + +### Example + +```ruby +# bad +CONST = 1.freeze + +# good +CONST = 1 +``` + +## Style/RedundantParentheses + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for redundant parentheses. + +### Example + +```ruby +# bad +(x) if ((y.z).nil?) + +# good +x if y.z.nil? +``` + +## Style/RedundantReturn + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for redundant `return` expressions. + +It should be extended to handle methods whose body is if/else +or a case expression with a default branch. + +### Example + +```ruby +def test + return something +end + +def test + one + two + three + return something +end +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AllowMultipleReturnValues | false| | + + +## Style/RedundantSelf + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for redundant uses of `self`. + +`self` is only needed when: + +* Sending a message to same object with zero arguments in + presence of a method name clash with an argument or a local + variable. + + Note, with using explicit self you can only send messages + with public or protected scope, you cannot send private + messages this way. + + Example: + + 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 + +* Calling an attribute writer to prevent an local variable assignment + + attr_writer :bar + + def foo + self.bar= 1 # Make sure above attr writer is called + end + +Special cases: + +We allow uses of `self` with operators because it would be awkward +otherwise. + +## Style/RegexpLiteral + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop enforces using // or %r around regular expressions. + +### Example + +```ruby +# Good if EnforcedStyle is slashes or mixed, bad if percent_r. +snake_case = /^[\dA-Z_]+$/ + +# Good if EnforcedStyle is percent_r, bad if slashes or mixed. +snake_case = %r{^[\dA-Z_]+$} + +# Good if EnforcedStyle is slashes, bad if percent_r or mixed. +regex = / + foo + (bar) + (baz) +/x + +# Good if EnforcedStyle is percent_r or mixed, bad if slashes. +regex = %r{ + foo + (bar) + (baz) +}x + +# Bad unless AllowInnerSlashes is true. +x =~ /home\// +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | slashes| | +SupportedStyles | slashes, percent_r, mixed| | +AllowInnerSlashes | false| | + + +## Style/RescueEnsureAlignment + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks whether the rescue and ensure keywords are aligned +properly. + +### Example + +```ruby +# bad +begin + something + rescue + puts 'error' +end + +# good +begin + something +rescue + puts 'error' +end +``` + +## Style/RescueModifier + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for uses of rescue in its modifier form. + +## Style/SafeNavigation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop transforms usages of a method call safeguarded by a non `nil` +check for the variable whose method is being called to +safe navigation (`&.`). + +Configuration option: ConvertCodeThatCanStartToReturnNil +The default for this is `false`. When configured to `true`, this will +check for code in the format `!foo.nil? && foo.bar`. As it is written, +the return of this code is limited to `false` and whatever the return +of the method is. If this is converted to safe navigation, +`foo&.bar` can start returning `nil` as well as what the method +returns. + +### Example + +```ruby +# bad +foo.bar if foo +foo.bar(param1, param2) if foo +foo.bar { |e| e.something } if foo +foo.bar(param) { |e| e.something } if foo + +foo.bar if !foo.nil? +foo.bar unless !foo +foo.bar unless foo.nil? + +foo && foo.bar +foo && foo.bar(param1, param2) +foo && foo.bar { |e| e.something } +foo && foo.bar(param) { |e| e.something } + +# good +foo&.bar +foo&.bar(param1, param2) +foo&.bar { |e| e.something } +foo&.bar(param) { |e| e.something } + +foo.nil? || foo.bar +!foo || foo.bar + +# Methods that `nil` will `respond_to?` should not be converted to +# use safe navigation +foo.to_i if foo +``` + +### Important attributes + +Attribute | Value | +--- | --- | +ConvertCodeThatCanStartToReturnNil | false| | + + +## Style/SelfAssignment + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop enforces the use the shorthand for self-assignment. + +### Example + +```ruby +# bad +x = x + 1 + +# good +x += 1 +``` + +## Style/Semicolon + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for multiple expressions placed on the same line. +It also checks for lines terminated with a semicolon. + +### Important attributes + +Attribute | Value | +--- | --- | +AllowAsExpressionSeparator | false| | + + +## Style/Send + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for the use of the send method. + +## Style/SignalException + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for uses of `fail` and `raise`. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | only_raise| | +SupportedStyles | only_raise, only_fail, semantic| | + + +## Style/SingleLineBlockParams + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop checks whether the block parameters of a single-line +method accepting a block match the names specified via configuration. + +For instance one can configure `reduce`(`inject`) to use |a, e| as +parameters. + +### Important attributes + +Attribute | Value | +--- | --- | +Methods | {"reduce"=>["a", "e"]}, {"inject"=>["a", "e"]}| | + + +## Style/SingleLineMethods + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for single-line method definitions. +It can optionally accept single-line methods with no body. + +### Important attributes + +Attribute | Value | +--- | --- | +AllowIfMethodIsEmpty | true| | + + +## Style/SpaceAfterColon + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for colon (:) not followed by some kind of space. +N.B. this cop does not handle spaces after a ternary operator, which are +instead handled by Style/SpaceAroundOperators. + +## Style/SpaceAfterComma + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for comma (,) not followed by some kind of space. + +## Style/SpaceAfterMethodName + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for space between a method name and a left parenthesis in defs. + +### Example + +```ruby +# bad +def func (x) ... end + +# good +def func(x) ... end +``` + +## Style/SpaceAfterNot + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for space after `!`. + +### Example + +```ruby +# bad +! something + +# good +!something +``` + +## Style/SpaceAfterSemicolon + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for semicolon (;) not followed by some kind of space. + +## Style/SpaceAroundBlockParameters + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks the spacing inside and after block parameters pipes. + +### Example + +```ruby +# bad +{}.each { | x, y |puts x } + +# good +{}.each { |x, y| puts x } +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyleInsidePipes | no_space| | +SupportedStyles | space, no_space| | + + +## Style/SpaceAroundEqualsInParameterDefault + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks that the equals signs in parameter default assignments +have or don't have surrounding space depending on configuration. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | space| | +SupportedStyles | space, no_space| | + + +## Style/SpaceAroundKeyword + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks the spacing around the keywords. + +### Example + +```ruby +# bad +something 'test'do|x| +end + +while(something) +end + +something = 123if test + +# good +something 'test' do |x| +end + +while (something) +end + +something = 123 if test +``` + +## Style/SpaceAroundOperators + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks that operators have space around them, except for ** +which should not have surrounding space. + +### Important attributes + +Attribute | Value | +--- | --- | +AllowForAlignment | true| | + + +## Style/SpaceBeforeBlockBraces + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks that block braces have or don't have a space before the opening +brace depending on configuration. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | space| | +SupportedStyles | space, no_space| | + + +## Style/SpaceBeforeComma + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for comma (,) preceded by space. + +## Style/SpaceBeforeComment + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for missing space between a token and a comment on the +same line. + +## Style/SpaceBeforeFirstArg + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks that exactly one space is used between a method name and the +first argument for method calls without parentheses. + +Alternatively, extra spaces can be added to align the argument with +something on a preceding or following line, if the AllowForAlignment +config parameter is true. + +### Example + +```ruby +# bad +something x +something y, z +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AllowForAlignment | true| | + + +## Style/SpaceBeforeSemicolon + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for semicolon (;) preceded by space. + +## Style/SpaceInsideArrayPercentLiteral + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for unnecessary additional spaces inside array percent literals +(i.e. %i/%w). + +### Example + +```ruby +# good +%i(foo bar baz) + +# bad +%w(foo bar baz) +``` + +## Style/SpaceInsideBlockBraces + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks that block braces have or don't have surrounding space inside +them on configuration. For blocks taking parameters, it checks that the +left brace has or doesn't have trailing space depending on +configuration. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | space| | +SupportedStyles | space, no_space| | +EnforcedStyleForEmptyBraces | no_space| | +SpaceBeforeBlockParameters | true| | + + +## Style/SpaceInsideBrackets + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for spaces inside square brackets. + +## Style/SpaceInsideHashLiteralBraces + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks that braces used for hash literals have or don't have +surrounding space depending on configuration. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | space| | +EnforcedStyleForEmptyBraces | no_space| | +SupportedStyles | space, no_space, compact| | + + +## Style/SpaceInsideParens + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for spaces inside ordinary round parentheses. + +## Style/SpaceInsidePercentLiteralDelimiters + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for unnecessary additional spaces inside the delimiters of +%i/%w/%x literals. + +### Example + +```ruby +# good +%i(foo bar baz) + +# bad +%w( foo bar baz ) + +# bad +%x( ls -l ) +``` + +## Style/SpaceInsideRangeLiteral + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for spaces inside range literals. + +### Example + +```ruby +# bad +1 .. 3 + +# good +1..3 + +# bad +'a' .. 'z' + +# good +'a'..'z' +``` + +## Style/SpaceInsideStringInterpolation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for whitespace within string interpolations. + +### Example + +```ruby +# Good if EnforcedStyle is no_space, bad if space. + var = "This is the #{no_space} example" + +# Good if EnforceStyle is space, bad if no_space. + var = "This is the #{ space } example" +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | no_space| | +SupportedStyles | space, no_space| | + + +## Style/SpecialGlobalVars + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop looks for uses of Perl-style global variables. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | use_english_names| | +SupportedStyles | use_perl_names, use_english_names| | + + +## Style/StabbyLambdaParentheses + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Check for parentheses around stabby lambda arguments. +There are two different styles. Defaults to `require_parentheses`. + +### Example + +```ruby +# require_parentheses - bad +->a,b,c { a + b + c } + +# require_parentheses - good +->(a,b,c) { a + b + c} + +# require_no_parentheses - bad +->(a,b,c) { a + b + c } + +# require_no_parentheses - good +->a,b,c { a + b + c} +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | require_parentheses| | +SupportedStyles | require_parentheses, require_no_parentheses| | + + +## Style/StringLiterals + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks if uses of quotes match the configured preference. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | single_quotes| | +SupportedStyles | single_quotes, double_quotes| | +ConsistentQuotesInMultiline | false| | + + +## Style/StringLiteralsInInterpolation + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks if uses of quotes match the configured preference. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | single_quotes| | +SupportedStyles | single_quotes, double_quotes| | + + +## Style/StringMethods + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop enforces the use of consistent method names +from the String class. + +### Important attributes + +Attribute | Value | +--- | --- | +PreferredMethods | {"intern"=>"to_sym"}| | + + +## Style/StructInheritance + +Enabled by default | Supports autocorrection +--- | --- +Enabled | No + +This cop checks for inheritance from Struct.new. + +### Example + +```ruby +# bad +class Person < Struct.new(:first_name, :last_name) +end + +# good +Person = Struct.new(:first_name, :last_name) +``` + +## Style/SymbolArray + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop can check for array literals made up of symbols that are not +using the %i() syntax. + +Alternatively, it checks for symbol arrays using the %i() syntax on +projects which do not want to use that syntax, perhaps because they +support a version of Ruby lower than 2.0. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | percent| | +SupportedStyles | percent, brackets| | + + +## Style/SymbolLiteral + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks symbol literal syntax. + +### Example + +```ruby +# bad +:"symbol" + +# good +:symbol +``` + +## Style/SymbolProc + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Use symbols as procs when possible. + +### Example + +```ruby +# bad +something.map { |s| s.upcase } + +# good +something.map(&:upcase) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +IgnoredMethods | respond_to, define_method| | + + +## Style/Tab + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for tabs inside the source code. + +## Style/TernaryParentheses + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for the presence of parentheses around ternary +conditions. It is configurable to enforce inclusion or omission of +parentheses using `EnforcedStyle`. + +### Example + +```ruby +EnforcedStyle: require_no_parentheses (default) + +# bad +foo = (bar?) ? a : b +foo = (bar.baz) ? a : b +foo = (bar && baz) ? a : b + +# good +foo = bar? ? a : b +foo = bar.baz? ? a : b +foo = bar && baz ? a : b +``` +```ruby +EnforcedStyle: require_parentheses + +# bad +foo = bar? ? a : b +foo = bar.baz? ? a : b +foo = bar && baz ? a : b + +# good +foo = (bar?) ? a : b +foo = (bar.baz) ? a : b +foo = (bar && baz) ? a : b +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | require_no_parentheses| | +SupportedStyles | require_parentheses, require_no_parentheses| | +AllowSafeAssignment | true| | + + +## Style/TrailingBlankLines + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop looks for trailing blank lines and a final newline in the +source code. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | final_newline| | +SupportedStyles | final_newline, final_blank_line| | + + +## Style/TrailingCommaInArguments + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for trailing comma in argument lists. + +### Example + +```ruby +# always bad +method(1, 2,) + +# good if EnforcedStyleForMultiline is consistent_comma +method( + 1, 2, + 3, +) + +# good if EnforcedStyleForMultiline is comma or consistent_comma +method( + 1, + 2, +) + +# good if EnforcedStyleForMultiline is no_comma +method( + 1, + 2 +) +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyleForMultiline | no_comma| | +SupportedStyles | comma, consistent_comma, no_comma| | + + +## Style/TrailingCommaInLiteral + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for trailing comma in array and hash literals. + +### Example + +```ruby +# 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 +] +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyleForMultiline | no_comma| | +SupportedStyles | comma, consistent_comma, no_comma| | + + +## Style/TrailingUnderscoreVariable + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop checks for extra underscores in variable assignment. + +### Example + +```ruby +# bad +a, b, _ = foo() +a, b, _, = foo() +a, _, _ = foo() +a, _, _, = foo() + +#good +a, b, = foo() +a, = foo() +*a, b, _ = foo() => We need to know to not include 2 variables in a +a, *b, _ = foo() => The correction `a, *b, = foo()` is a syntax error +``` + +### Important attributes + +Attribute | Value | +--- | --- | +AllowNamedUnderscoreVariables | true| | + + +## Style/TrailingWhitespace + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop looks for trailing whitespace in the source code. + +## Style/TrivialAccessors + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop looks for trivial reader/writer methods, that could +have been created with the attr_* family of functions automatically. + +### Important attributes + +Attribute | Value | +--- | --- | +ExactNameMatch | true| | +AllowPredicates | true| | +AllowDSLWriters | false| | +IgnoreClassMethods | false| | +Whitelist | to_ary, to_a, to_c, to_enum, to_h, to_hash, to_i, to_int, to_io, to_open, to_path, to_proc, to_r, to_regexp, to_str, to_s, to_sym| | + + +## Style/UnlessElse + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop looks for *unless* expressions with *else* clauses. + +## Style/UnneededCapitalW + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for usage of the %W() syntax when %w() would do. + +## Style/UnneededInterpolation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for strings that are just an interpolated expression. + +### Example + +```ruby +# bad +"#{@var}" + +# good +@var.to_s + +# good if @var is already a String +@var +``` + +## Style/UnneededPercentQ + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for usage of the %q/%Q syntax when '' or "" would do. + +## Style/VariableInterpolation + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for variable interpolation (like "#@ivar"). + +## Style/VariableName + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop makes sure that all variables use the configured style, +snake_case or camelCase, for their names. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | snake_case| | +SupportedStyles | snake_case, camelCase| | + + +## Style/VariableNumber + +Enabled by default | Supports autocorrection +--- | --- +Disabled | No + +This cop makes sure that all numbered variables use the +configured style, snake_case, normalcase or non_integer, +for their numbering. + +### Example + +```ruby +"EnforcedStyle => 'snake_case'" + +# bad + +variable1 = 1 + +# good + +variable_1 = 1 +``` +```ruby +"EnforcedStyle => 'normalcase'" + +# bad + +variable_1 = 1 + +# good + +variable1 = 1 +``` +```ruby +"EnforcedStyle => 'non_integer'" + +#bad + +variable1 = 1 + +variable_1 = 1 + +#good + +variableone = 1 + +variable_one = 1 +``` + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | normalcase| | +SupportedStyles | snake_case, normalcase, non_integer| | + + +## Style/WhenThen + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for *when;* uses in *case* expressions. + +## Style/WhileUntilDo + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +Checks for uses of `do` in multi-line `while/until` statements. + +## Style/WhileUntilModifier + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +Checks for while and until statements that would fit on one line +if written as a modifier while/until. +The maximum line length is configurable. + +### Important attributes + +Attribute | Value | +--- | --- | +MaxLineLength | 80| | + + +## Style/WordArray + +Enabled by default | Supports autocorrection +--- | --- +Disabled | Yes + +This cop can check for array literals made up of word-like +strings, that are not using the %w() syntax. + +Alternatively, it can check for uses of the %w() syntax, in projects +which do not want to include that syntax. + +### Important attributes + +Attribute | Value | +--- | --- | +EnforcedStyle | percent| | +SupportedStyles | percent, brackets| | +MinSize | 0| | +WordRegex | (?-mix:\A[\p{Word}\n\t]+\z)| | + + +## Style/ZeroLengthPredicate + +Enabled by default | Supports autocorrection +--- | --- +Enabled | Yes + +This cop checks for receiver.length == 0 predicates and the +negated versions receiver.length > 0 and receiver.length != 0. +These can be replaced with receiver.empty? and +!receiver.empty? respectively. + +### Example + +```ruby +# bad +[1, 2, 3].length == 0 +0 == "foobar".length +hash.size > 0 + +# good +[1, 2, 3].empty? +"foobar".empty? +!hash.empty? +``` diff --git a/spec/rubocop/cop/style/space_inside_array_percent_literal_spec.rb b/spec/rubocop/cop/style/space_inside_array_percent_literal_spec.rb index 46d4e6846945..f89980484174 100644 --- a/spec/rubocop/cop/style/space_inside_array_percent_literal_spec.rb +++ b/spec/rubocop/cop/style/space_inside_array_percent_literal_spec.rb @@ -8,7 +8,7 @@ %w(i I w W).each do |type| [%w({ }), %w{( )}, %w([ ]), %w(! !)].each do |(ldelim, rdelim)| context "for #{type} type and #{[ldelim, rdelim]} delimiters" do - define_method(:example) do |content| + define_method(:code_example) do |content| ['%', type, ldelim, content, rdelim].join end @@ -17,35 +17,35 @@ def expect_corrected(source, expected) end it 'registers an offense for unnecessary spaces' do - source = example('1 2') + source = code_example('1 2') inspect_source(cop, source) expect(cop.offenses.size).to eq(1) expect(cop.highlights).to eq([' ']) expect(cop.messages).to eq([described_class::MSG]) - expect_corrected(source, example('1 2')) + expect_corrected(source, code_example('1 2')) end it 'registers an offense for multiple spaces between items' do - source = example('1 2 3') + source = code_example('1 2 3') inspect_source(cop, source) expect(cop.offenses.size).to eq(2) - expect_corrected(source, example('1 2 3')) + expect_corrected(source, code_example('1 2 3')) end it 'accepts literals with escaped and additional spaces' do - source = example('a\ b \ c') + source = code_example('a\ b \ c') inspect_source(cop, source) expect(cop.offenses.size).to eq(1) - expect_corrected(source, example('a\ b \ c')) + expect_corrected(source, code_example('a\ b \ c')) end it 'accepts literals without additional spaces' do - inspect_source(cop, example('a b c')) + inspect_source(cop, code_example('a b c')) expect(cop.messages).to be_empty end it 'accepts literals with escaped spaces' do - inspect_source(cop, example('a\ b\ \ c')) + inspect_source(cop, code_example('a\ b\ \ c')) expect(cop.messages).to be_empty end diff --git a/spec/rubocop/cop/style/space_inside_percent_literal_delimiters_spec.rb b/spec/rubocop/cop/style/space_inside_percent_literal_delimiters_spec.rb index 1fbdd2a05dba..15b759238c66 100644 --- a/spec/rubocop/cop/style/space_inside_percent_literal_delimiters_spec.rb +++ b/spec/rubocop/cop/style/space_inside_percent_literal_delimiters_spec.rb @@ -8,7 +8,7 @@ %w(i I w W x).each do |type| [%w({ }), %w{( )}, %w([ ]), %w(! !)].each do |(ldelim, rdelim)| context "for #{type} type and #{[ldelim, rdelim]} delimiters" do - define_method(:example) do |content| + define_method(:code_example) do |content| ['%', type, ldelim, content, rdelim].join end @@ -17,42 +17,42 @@ def expect_corrected(source, expected) end it 'registers an offense for unnecessary spaces' do - source = example(' 1 2 ') + source = code_example(' 1 2 ') inspect_source(cop, source) expect(cop.offenses.size).to eq(2) expect(cop.messages.uniq).to eq([described_class::MSG]) expect(cop.highlights).to eq([' ', ' ']) - expect_corrected(source, example('1 2')) + expect_corrected(source, code_example('1 2')) end it 'registers an offense for spaces after first delimiter' do - source = example(' 1 2') + source = code_example(' 1 2') inspect_source(cop, source) expect(cop.offenses.size).to eq(1) - expect_corrected(source, example('1 2')) + expect_corrected(source, code_example('1 2')) end it 'registers an offense for spaces before final delimiter' do - source = example('1 2 ') + source = code_example('1 2 ') inspect_source(cop, source) expect(cop.offenses.size).to eq(1) - expect_corrected(source, example('1 2')) + expect_corrected(source, code_example('1 2')) end it 'registers an offense for literals with escaped and other spaces' do - source = example(' \ a b c\ ') + source = code_example(' \ a b c\ ') inspect_source(cop, source) expect(cop.offenses.size).to eq(2) - expect_corrected(source, example('\ a b c\ ')) + expect_corrected(source, code_example('\ a b c\ ')) end it 'accepts literals without additional spaces' do - inspect_source(cop, example('a b c')) + inspect_source(cop, code_example('a b c')) expect(cop.messages).to be_empty end it 'accepts literals with escaped spaces' do - inspect_source(cop, example('\ a b c\ ')) + inspect_source(cop, code_example('\ a b c\ ')) expect(cop.messages).to be_empty end @@ -83,7 +83,7 @@ def expect_corrected(source, expected) end it 'accepts spaces between entries' do - inspect_source(cop, example('a b c')) + inspect_source(cop, code_example('a b c')) expect(cop.messages).to be_empty end end diff --git a/tasks/cops_documentation.rake b/tasks/cops_documentation.rake new file mode 100644 index 000000000000..4049f360d4ab --- /dev/null +++ b/tasks/cops_documentation.rake @@ -0,0 +1,113 @@ +# frozen_string_literal: true +require 'yard' +require 'rubocop' + +desc 'Generate docs of all cops types' + +task :generate_cops_documentation do |_task| + def cop_name_without_type(cop_name) + cop_name.split('/').last.to_sym + end + + def cops_of_type(cops, type) + cops.with_type(type).sort_by!(&:cop_name) + end + + def cops_body(config, cop, description, examples_objects, pars) + content = h2(cop.cop_name) + content << properties(config, cop) + content << "\n\n" + content << "#{description}\n" + content << examples(examples_objects) if examples_objects.count > 0 + content << default_settings(pars) + content + end + + def examples(examples_object) + content = h3('Example') + content += examples_object.map { |e| code_example(e) }.join + content + end + + def properties(config, cop) + content = "Enabled by default | Supports autocorrection\n" + content << "--- | ---\n" + default_status = config.cop_enabled?(cop) ? 'Enabled' : 'Disabled' + supports_autocorrect = cop.new.support_autocorrect? ? 'Yes' : 'No' + content << "#{default_status} | #{supports_autocorrect}" + content + end + + def h2(title) + content = "\n" + content << "## #{title}\n" + content << "\n" + content + end + + def h3(title) + content = "\n" + content << "### #{title}\n" + content << "\n" + content + end + + def code_example(ruby_code) + content = "```ruby\n" + content << ruby_code.text.gsub('@good', '# good') + .gsub('@bad', '# bad').strip + content << "\n```\n" + content + end + + def default_settings(pars) + return '' unless pars.keys.count > 0 + content = h3('Important attributes') + content << "Attribute | Value |\n" + content << "--- | --- |\n" + pars.each do |par| + content << "#{par.first} | #{format_table_value(par.last)} |\n" + end + content << "\n" + content + end + + def format_table_value(v) + value = v.is_a?(Array) ? v.join(', ') : v.to_s + value.gsub(Dir.pwd, '') << '|' + end + + def print_cops_of_type(cops, type, config) + selected_cops = cops_of_type(cops, type) + content = "# #{type.capitalize}\n" + selected_cops.each do |cop| + content << print_cop_with_doc(cop, config) + end + file_name = "#{Dir.pwd}/manual/cops_#{type}.md" + file = File.open(file_name, 'w') + puts "* generated #{file_name}" + file.write(content) + end + + def print_cop_with_doc(cop, config) + t = config.for_cop(cop) + pars = t.reject! { |k| %w(Description Enabled StyleGuide).include? k } + description = 'No documentation' + examples_object = [] + YARD::Registry.all.select { |o| !o.docstring.blank? }.map do |o| + if o.name == cop_name_without_type(cop.cop_name) + description = o.docstring + examples_object = o.tags('example') + end + end + cops_body(config, cop, description, examples_object, pars) + end + + puts 'This generator uses the comments and tags (`@example`) for the '\ + 'generation. Please use `yardoc` before running this script to make '\ + 'sure, that all your changes were rendered.' + cops = RuboCop::Cop::Cop.all + config = RuboCop::ConfigStore.new.for(Dir.pwd) + YARD::Registry.load! + cops.types.sort!.each { |type| print_cops_of_type(cops, type, config) } +end diff --git a/tasks/new_cop.rake b/tasks/new_cop.rake index a22d14029090..d1e3a32e0409 100644 --- a/tasks/new_cop.rake +++ b/tasks/new_cop.rake @@ -20,6 +20,7 @@ task :new_cop, [:cop] do |_task, args| cop_code = <<-END # frozen_string_literal: true +# TODO: when finished, run 1) `yardoc` and 2) `rake generate_cops_documentation` to update the docs module RuboCop module Cop module #{category}