Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Last active July 6, 2020 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmartin/7fb67c7aec05e7b448e046844ac0029d to your computer and use it in GitHub Desktop.
Save jamesmartin/7fb67c7aec05e7b448e046844ac0029d to your computer and use it in GitHub Desktop.
Notes on writing custom RuboCop Cops

To match on string interpolation:

module MyCops
  class MyGreatCop < Cop
  include Interpolation # <- required when attempting to match on_interpolation
  
  def on_interpolation(node)
    # Using node.parent gets you the String rather than the interpolation
    if /foo/.match(begin_node.parent.source)
      add_offense(begin_node.parent, location: :expression)
    end
  end

To test only your custom cop against some arbitrary input:

bin/rubocop -d --only MyCops/MyGreatCop -stmp/rubocop.out
# Some ruby code to lint:
1 + 1
CTRL^D

Configuring exceptions for your custom Cop:

# rubocop.yml

MyCops/MyGreatCop
  Enabled: true
  StyleGuide: https://example.com/styleguide
  Include:
    - 'test/**/*.rb'
  Exclude:
    - 'app/models/*.rb'

To disable your custom cop temorarily:

# rubocop:disable MyCops/MyGreatCop
some_bad_code
# rubocop:enable MyCops/MyGreatCop

# or...

some_bad_code #rubocop:disable MyCops/MyGreatCop

# or...

# rubocop:todo #MyCops/MyGreatCop
some_bad_code
# rubocop:enable MyCops/MyGreatCop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment