Implementing a custom RuboCop cop

Updated . Posted . Visible to the public. Repeats.

It's possible to implement simple custom RuboCop cops with very little code. They work exactly the same like existing rubocop cops and fail the pipeline if they find an offense. This is handy for project specific internal rules or conventions.

The following cop looks at every ruby file and searches for TODO or WIP comments and adds an offense.

class NoTodos < RuboCop::Cop::Base
  MSG = "Don't add TODOs & WIPs in the source."

  def on_new_investigation
    processed_source.comments.each { |comment| search_for_forbidden_annotation(comment) }
  end

  private

  def search_for_forbidden_annotation(comment)
    add_offense(comment.source_range) if comment.source.match?(/TODO|WIP/i)
  end
end

Custom cops have to be required in the .rubocop.yml:

require:
  - ./lib/cops/no_todos.rb

Your cop has the same output as existing cops if it finds an offense:

Offenses:

app/models/test.rb:36:3: C: NoTodos: Don't add TODOs & WIPs in the source.

  # TODO: foobar
  ^^^^^^^^^^^^^^

Make sure to check all the existing cops Show archive.org snapshot if you need inspiration how to implement a specific cop.

Niklas Hä.
Last edit
Julian
License
Source code in this card is licensed under the MIT License.
Posted by Niklas Hä. to makandra dev (2024-09-20 06:16)