Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Rubocop Configuration Files for Rails
Truemark Technology profile imagePrabin Poudel
Prabin Poudel forTruemark Technology

Posted on • Originally published atprabinpoudel.com.np

     

Rubocop Configuration Files for Rails

I spent a whole day configuring Rubocop in one of our Rails project. I am here to save your day's worth of time.

Rubocop is a linter for Ruby and Rails Projects. It enforces best practices based on the guidelines outlined in the communityRuby Style Guide. Apart from reporting the problems discovered in your code, RuboCop can also automatically fix many of them for you.

Configuration for Rails

This project assumes that you have already setup rubocop in your project and have.rubocop.yml.

Step 1: Add rules to.rubocop.yml

# The behavior of RuboCop can be controlled via the .rubocop.yml# configuration file. It makes it possible to enable/disable# certain cops (checks) and to alter their behavior if they accept# any parameters. The file can be placed either in your home# directory or in some project directory.## RuboCop will start looking for the configuration file in the directory# where the inspected file is and continue its way up to the root directory.#inherit_from:-'.rubocop-rails.yml'-'.rubocop-rspec.yml'require:-rubocop-rails-rubocop-rspecAllCops:TargetRubyVersion:2.7TargetRailsVersion:6.0Exclude:-'**/db/migrate/*'-'**/Gemfile.lock'-'**/Rakefile'-'**/rails'-'**/vendor/**/*'-'**/spec_helper.rb'-'node_modules/**/*'-'bin/*'################################################################################# Rubocop ######################################################################################## You can find all configuration options for rubocop here: https://docs.rubocop.org/rubocop/cops_bundler.html# ============== Layout =================Layout/ClassStructure:ExpectedOrder:-module_inclusion-constants-association-public_attribute_macros-public_delegate-macros-initializer-public_class_methods-public_methods-protected_attribute_macros-protected_methods-private_attribute_macros-private_delegate-private_methodsLayout/EmptyLineAfterMultilineCondition:Enabled:trueLayout/EmptyLinesAroundAttributeAccessor:Enabled:trueLayout/FirstArrayElementIndentation:EnforcedStyle:consistentLayout/FirstArrayElementLineBreak:Enabled:trueLayout/FirstHashElementIndentation:EnforcedStyle:consistentLayout/FirstHashElementLineBreak:Enabled:trueLayout/LineLength:Max:150Exclude:-'**/spec/**/*'Layout/MultilineArrayBraceLayout:EnforcedStyle:new_lineLayout/MultilineOperationIndentation:EnforcedStyle:indentedLayout/MultilineHashBraceLayout:EnforcedStyle:new_lineLayout/MultilineHashKeyLineBreaks:Enabled:trueLayout/MultilineMethodCallBraceLayout:EnforcedStyle:new_lineLayout/MultilineMethodDefinitionBraceLayout:EnforcedStyle:new_lineLayout/SpaceAroundMethodCallOperator:Enabled:trueLayout/SpaceInLambdaLiteral:EnforcedStyle:require_spaceLint/AmbiguousBlockAssociation:Exclude:-'**/spec/**/*'Lint/AssignmentInCondition:AllowSafeAssignment:falseLint/BinaryOperatorWithIdenticalOperands:Enabled:trueLint/DeprecatedOpenSSLConstant:Enabled:trueLint/DuplicateElsifCondition:Enabled:trueLint/DuplicateRequire:Enabled:trueLint/DuplicateRescueException:Enabled:trueLint/EmptyConditionalBody:Enabled:trueLint/EmptyFile:Enabled:trueLint/FloatComparison:Enabled:trueLint/MissingSuper:Enabled:trueLint/MixedRegexpCaptureTypes:Enabled:trueLint/NumberConversion:Enabled:trueLint/RaiseException:Enabled:trueLint/SelfAssignment:Enabled:trueLint/TrailingCommaInAttributeDeclaration:Enabled:trueLint/UnusedBlockArgument:IgnoreEmptyBlocks:falseLint/UnusedMethodArgument:IgnoreEmptyMethods:falseLint/UselessMethodDefinition:Enabled:true# ============== Metric =================Metrics/AbcSize:Max:45Metrics/BlockLength:CountComments:falseMax:50Exclude:-'**/spec/**/*'-'**/*.rake'-'**/factories/**/*'-'**/config/routes.rb'Metrics/ClassLength:CountAsOne:['array','hash']Max:150Metrics/CyclomaticComplexity:Max:10Metrics/MethodLength:CountAsOne:['array','hash']Max:30Metrics/ModuleLength:CountAsOne:['array','hash']Max:250Exclude:-'**/spec/**/*'Metrics/PerceivedComplexity:Max:10# ============== Variable ==================# Most of the Naming configurations are enabled by default, we should enable or disable configuration depending on what the team needs### Example###  Naming/VariableNumber:#    Enabled: false###### ============== Style ================Style/AccessorGrouping:Enabled:trueStyle/ArrayCoercion:Enabled:trueStyle/AutoResourceCleanup:Enabled:trueStyle/BisectedAttrAccessor:Enabled:trueStyle/CaseLikeIf:Enabled:trueStyle/ClassAndModuleChildren:Enabled:falseStyle/CollectionMethods:Enabled:trueStyle/CombinableLoops:Enabled:trueStyle/CommandLiteral:EnforcedStyle:percent_xStyle/ConstantVisibility:Enabled:trueStyle/Documentation:Enabled:falseStyle/ExplicitBlockArgument:Enabled:trueStyle/GlobalStdStream:Enabled:trueStyle/HashEachMethods:Enabled:trueStyle/HashLikeCase:Enabled:trueStyle/HashTransformKeys:Enabled:trueStyle/HashTransformValues:Enabled:trueStyle/ImplicitRuntimeError:Enabled:trueStyle/InlineComment:Enabled:trueStyle/IpAddresses:Enabled:trueStyle/KeywordParametersOrder:Enabled:trueStyle/MethodCallWithArgsParentheses:Enabled:trueStyle/MissingElse:Enabled:trueStyle/MultilineMethodSignature:Enabled:trueStyle/OptionalBooleanParameter:Enabled:trueStyle/RedundantAssignment:Enabled:trueStyle/RedundantBegin:Enabled:trueStyle/RedundantFetchBlock:Enabled:trueStyle/RedundantFileExtensionInRequire:Enabled:trueStyle/RedundantSelfAssignment:Enabled:trueStyle/SingleArgumentDig:Enabled:trueStyle/StringConcatenation:Enabled:true
Enter fullscreen modeExit fullscreen mode

Step 2: Create.rubocop-rails.yml

Above file enforces all best practices for Ruby code, now we will be adding configuration explicit for Rails.

Create.rubocop-rails.yml if you haven't already and add the following inside it:

############################################################################### Rubocop Rails #################################################################################### You can find all configuration options for rubocop-rails here: https://docs.rubocop.org/rubocop-rails/cops_rails.htmlRails/ActiveRecordCallbacksOrder:Enabled:trueRails/AfterCommitOverride:Enabled:trueRails/DefaultScope:Enabled:trueRails/FindById:Enabled:trueRails/Inquiry:Enabled:trueRails/MailerName:Enabled:trueRails/MatchRoute:Enabled:trueRails/NegateInclude:Enabled:trueRails/OrderById:Enabled:trueRails/Pluck:Enabled:trueRails/PluckId:Enabled:trueRails/PluckInWhere:Enabled:trueRails/RenderInline:Enabled:trueRails/RenderPlainText:Enabled:trueRails/SaveBang:Enabled:trueAllowImplicitReturn:falseRails/ShortI18n:Enabled:trueRails/WhereExists:Enabled:trueRails/WhereNot:Enabled:true
Enter fullscreen modeExit fullscreen mode

Bonus: Configuration for RSpec

NOTE: You should already have setup therubocop-rspec gem.

Create.rubocop-rspec.yml in the root project and add the following:

############################################################################### Rubocop Rspec #################################################################################### You can find all configuration options for rubocop-rspec here: https://docs.rubocop.org/rubocop-rspec/cops.htmlRSpec/AnyInstance:Enabled:falseRSpec/BeforeAfterAll:Enabled:falseRSpec/ContextWording:Enabled:falseRSpec/DescribeClass:Enabled:falseRSpec/ExampleLength:Enabled:falseRSpec/ExpectInHook:Enabled:falseRSpec/FilePath:Enabled:falseRSpec/InstanceVariable:Enabled:falseRSpec/LetSetup:Enabled:falseRSpec/MessageChain:Enabled:falseRSpec/MessageSpies:Enabled:falseRSpec/MultipleExpectations:Enabled:falseRSpec/NamedSubject:Enabled:falseRSpec/NestedGroups:Max:7RSpec/SubjectStub:Enabled:falseRSpec/VerifiedDoubles:Enabled:falseRSpec/VoidExpect:Enabled:false
Enter fullscreen modeExit fullscreen mode

Conclusion

You should now have fully working configuration for Rubocop in your Rails application in like 2 minutes.

Please note that, these Rubcop rules are not hard-and-fast, you should add and remove rules from the configuration files based on the decisions of your team.

Thank you for reading, see you in the next blog.

Image Credits: Cover Image byTim Gouw onUnsplash

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

More fromTruemark Technology

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp