class RuboCop::Cop::Generator
and spec file when given a valid qualified cop name.
This generator will take a cop name and generate a source file
Source and spec generator for new cops
def generate(template)
def generate(template) format(template, department: badge.department, cop_name: badge.cop_name) end
def generated_source
def generated_source generate(SOURCE_TEMPLATE) end
def generated_spec
def generated_spec generate(SPEC_TEMPLATE) end
def initialize(name, github_user, output: $stdout)
def initialize(name, github_user, output: $stdout) @badge = Badge.parse(name) @github_user = github_user @output = output return if badge.qualified? raise ArgumentError, 'Specify a cop name with Department/Name style' end
def inject_config(config_file_path: 'config/enabled.yml')
def inject_config(config_file_path: 'config/enabled.yml') config = File.readlines(config_file_path) content = <<-YAML.strip_indent #{badge}: Description: 'TODO: Write a description of the cop.' Enabled: true YAML target_line = config.find.with_index(1) do |line, index| next if line =~ /^[\s#]/ break index - 1 if badge.to_s < line end config.insert(target_line, content) File.write(config_file_path, config.join) output.puts <<-MESSAGE.strip_indent [modify] A configuration for the cop is added into #{config_file_path}. If you want to disable the cop by default, move the added config to config/disabled.yml MESSAGE end
def inject_require(root_file_path: 'lib/rubocop.rb')
def inject_require(root_file_path: 'lib/rubocop.rb') RequireFileInjector.new( source_path: source_path, root_file_path: root_file_path ).inject end
def snake_case(camel_case_string)
def snake_case(camel_case_string) return 'rspec' if camel_case_string == 'RSpec' camel_case_string .gsub(/([^A-Z])([A-Z]+)/, '\1_\2') .gsub(/([A-Z])([A-Z][^A-Z\d]+)/, '\1_\2') .downcase end
def source_path
def source_path File.join( 'lib', 'rubocop', 'cop', snake_case(badge.department.to_s), "#{snake_case(badge.cop_name.to_s)}.rb" ) end
def spec_path
def spec_path File.join( 'spec', 'rubocop', 'cop', snake_case(badge.department.to_s), "#{snake_case(badge.cop_name.to_s)}_spec.rb" ) end
def todo
def todo <<-TODO.strip_indent Do 3 steps: 1. Add an entry to the "New features" section in CHANGELOG.md, e.g. "Add new `#{badge}` cop. ([@#{github_user}][])" 2. Modify the description of #{badge} in config/enabled.yml 3. Implement your new cop in the generated file! TODO end
def write_source
def write_source write_unless_file_exists(source_path, generated_source) end
def write_spec
def write_spec write_unless_file_exists(spec_path, generated_spec) end
def write_unless_file_exists(path, contents)
def write_unless_file_exists(path, contents) if File.exist?(path) warn "rake new_cop: #{path} already exists!" exit! end dir = File.dirname(path) FileUtils.mkdir_p(dir) unless File.exist?(dir) File.write(path, contents) output.puts "[create] #{path}" end