Rubocop – Coding With Style



Rubocop – Coding With Style

0 0


rubocop-talk


On Github skorfmann / rubocop-talk

Rubocop

Coding With Style

Created by Sebastian Korfmann / @skorfmann

Rubocop

“Role models are important.”

Officer Alex J. Murphy / RoboCop

What is Rubocop?

RuboCop is a Ruby static code analyzer.

Why should I care?

class MyClass
  attr_accessor :name

  def initalize name
    self.name = name
  end

  def name
    name.upcase
  rescue
  end

  def greet
    return 'Hello'+name
  end
end

Why Should I care?

rubocop --format offences

1  SpaceAroundOperators
1  RedundantReturn
1  HandleExceptions
1  MethodDefParentheses
1  Documentation
					

Why Should I care?

Community Stylguides

Ruby Example:

# starting point (line is too long)
def send_mail(source)
  Mailer.deliver(to: 'bob@example.com', from: 'us@example.com', subject: 'Important message', body: source.text)
end

# good (normal indent)
def send_mail(source)
  Mailer.deliver(
    to: 'bob@example.com',
    from: 'us@example.com',
    subject: 'Important message',
    body: source.text
  )
end

Community Styleguides

Rails Example

# bad
validates_presence_of :email

# good
validates :email, presence: true

Community Styleguides

  • Fork and adapt to your needs
  • Commit to its usage
  • Enforce it with RuboCop

Getting Started

Add it to your project

#Gemfile

gem 'rubocop'

1st RuboCop Run

Yeah, all right...

Incremental Approach

  • Ignore all Cops to get started
  • Enable and fix one Cop at a time

RuboCop Todo

rubocop --auto-gen-config
#./rubocop-todo.yml

# Offence count: 3
AccessorMethodName:
  Enabled: false

# Offence count: 7
# Cop supports --auto-correct.
AlignArray:
  Enabled: false

# Offence count: 20
# Cop supports --auto-correct.
# Configuration parameters: EnforcedHashRocketStyle, EnforcedColonStyle.
AlignHash:
  Enabled: false

#...
				

RuboCop Settings

#./rubocop-settings.yml
HashSyntax:
  EnforcedStyle: hash_rockets

Style/SpaceInsideHashLiteralBraces:
  EnforcedStyle: no_space

Style/NumericLiterals:
  Enabled: false

Style/SignalException:
  Enabled: false

Metrics/ClassLength:
  CountComments: false
  Max: 150

#...
				

Hacks

Violate the Styleguide on purpose:

# rubocop:disable RescueModifier
if (entity rescue nil)
# rubocop:enable RescueModifier
					

Enforce Style

Enforce Style

Enforce Style (Hosted)

Resources

Sebastian Korfmann

Freelance Software Engineer

@skorfmann

Thanks!

Sebastian Korfmann / @skorfmann