Created
November 11, 2019 23:12
-
-
Save anujbiyani/ec2629267368b4c5c2a915a938d39d39 to your computer and use it in GitHub Desktop.
Generate scaffold for new cop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
desc "Create a RuboCop rule using a template. You can use snake_case or CamelCase for the cop name; either way it will be converted to CamelCase." | |
task :generate_cop, [:name] do |_t, args| | |
require "active_support/inflector/methods" | |
camel_case_name = ActiveSupport::Inflector.camelize(args[:name], true) | |
snake_case_name = ActiveSupport::Inflector.underscore(camel_case_name) | |
cop_path = "lib/rubocop/cop/<company name>/#{snake_case_name}.rb" | |
spec_path = "spec/rubocop/cop/<company name>/#{snake_case_name}_spec.rb" | |
raise ArgumentError, "Cannot create cop -- file <#{cop_path}> already exists." if File.exist?(cop_path) | |
raise ArgumentError, "Cannot create spec -- file <#{spec_path}> already exists." if File.exist?(spec_path) | |
File.open(cop_path, "w") do |f| | |
f.write(<<~COP) | |
module RuboCop | |
module Cop | |
module CompanyName | |
# Description of what this cop does | |
# | |
# Can be multi-line | |
# | |
# @example | |
# | |
# # bad | |
# <example of bad code> | |
# | |
# # good | |
# <example of good code> | |
# | |
class #{camel_case_name} < Cop | |
MSG = "Failure message".freeze | |
end | |
end | |
end | |
end | |
COP | |
end | |
File.open(spec_path, "w") do |f| | |
f.write(<<~SPEC) | |
require "spec_helper" | |
RSpec.describe RuboCop::Cop::CompanyName::#{camel_case_name} do | |
subject(:cop) { described_class.new(config) } | |
let(:config) { RuboCop::Config.new } | |
context "when under some conditions" do | |
it "does not register an offense" do | |
skip("Specs are required for all cops.") | |
expect_no_offenses(<<~RUBY) | |
<good code> | |
RUBY | |
end | |
end | |
context "when under other conditions" do | |
it "registers an offense" do | |
skip("Specs are required for all cops.") | |
expect_offense(<<~RUBY) | |
<bad code> | |
^^^^^^^^^^ <Failure message> | |
RUBY | |
end | |
end | |
end | |
SPEC | |
end | |
File.open("lib/rubocop-companyName.rb", "a") do |f| | |
f.write("require \"rubocop/cop/<company name>/#{snake_case_name}\"\n") | |
end | |
File.open("config/default.yml", "a") do |f| | |
f.write(<<~YAML) | |
CompanyName/#{camel_case_name}: | |
Enabled: true | |
YAML | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment