1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Enable Start/EndWith and RegexpMatch cops

In cases where the MatchData object is not used, this provides a speed-up:
https://github.com/JuanitoFatas/fast-ruby/#stringmatch-vs-stringmatch-vs-stringstart_withstringend_with-code-start-code-end
This commit is contained in:
Bart de Water 2018-07-28 17:37:17 -04:00
parent 8741052ba2
commit eb5fea40a4
25 changed files with 42 additions and 33 deletions

View file

@ -193,3 +193,12 @@ Performance/FlatMap:
Performance/RedundantMerge: Performance/RedundantMerge:
Enabled: true Enabled: true
Performance/StartWith:
Enabled: true
Performance/EndWith:
Enabled: true
Performance/RegexpMatch:
Enabled: true

View file

@ -57,7 +57,7 @@ namespace :assets do
end end
print "[verify] #{file} is a UMD module " print "[verify] #{file} is a UMD module "
if pathname.read =~ /module\.exports.*define\.amd/m if /module\.exports.*define\.amd/m.match?(pathname.read)
puts "[OK]" puts "[OK]"
else else
$stderr.puts "[FAIL]" $stderr.puts "[FAIL]"

View file

@ -17,7 +17,7 @@ module AbstractController
@path = "helpers/#{path}.rb" @path = "helpers/#{path}.rb"
set_backtrace error.backtrace set_backtrace error.backtrace
if error.path =~ /^#{path}(\.rb)?$/ if /^#{path}(\.rb)?$/.match?(error.path)
super("Missing helper file helpers/%s.rb" % path) super("Missing helper file helpers/%s.rb" % path)
else else
raise error raise error

View file

@ -121,7 +121,7 @@ module ActionDispatch
# not contained within the headers hash. # not contained within the headers hash.
def env_name(key) def env_name(key)
key = key.to_s key = key.to_s
if key =~ HTTP_HEADER if HTTP_HEADER.match?(key)
key = key.upcase.tr("-", "_") key = key.upcase.tr("-", "_")
key = "HTTP_" + key unless CGI_VARIABLES.include?(key) key = "HTTP_" + key unless CGI_VARIABLES.include?(key)
end end

View file

@ -113,7 +113,7 @@ module ActionDispatch
cookies = cookies.split("\n".freeze) cookies = cookies.split("\n".freeze)
headers["Set-Cookie".freeze] = cookies.map { |cookie| headers["Set-Cookie".freeze] = cookies.map { |cookie|
if cookie !~ /;\s*secure\s*(;|$)/i if !/;\s*secure\s*(;|$)/i.match?(cookie)
"#{cookie}; secure" "#{cookie}; secure"
else else
cookie cookie

View file

@ -279,7 +279,7 @@ module ActionDispatch
def verify_regexp_requirements(requirements) def verify_regexp_requirements(requirements)
requirements.each do |requirement| requirements.each do |requirement|
if requirement.source =~ ANCHOR_CHARACTERS_REGEX if ANCHOR_CHARACTERS_REGEX.match?(requirement.source)
raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}" raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
end end
@ -333,7 +333,7 @@ module ActionDispatch
end end
def split_to(to) def split_to(to)
if to =~ /#/ if /#/.match?(to)
to.split("#") to.split("#")
else else
[] []
@ -342,7 +342,7 @@ module ActionDispatch
def add_controller_module(controller, modyoule) def add_controller_module(controller, modyoule)
if modyoule && !controller.is_a?(Regexp) if modyoule && !controller.is_a?(Regexp)
if controller =~ %r{\A/} if %r{\A/}.match?(controller)
controller[1..-1] controller[1..-1]
else else
[modyoule, controller].compact.join("/") [modyoule, controller].compact.join("/")
@ -1588,7 +1588,7 @@ module ActionDispatch
when Symbol when Symbol
options[:action] = to options[:action] = to
when String when String
if to =~ /#/ if /#/.match?(to)
options[:to] = to options[:to] = to
else else
options[:controller] = to options[:controller] = to
@ -1914,7 +1914,7 @@ module ActionDispatch
default_action = options.delete(:action) || @scope[:action] default_action = options.delete(:action) || @scope[:action]
if action =~ /^[\w\-\/]+$/ if /^[\w\-\/]+$/.match?(action)
default_action ||= action.tr("-", "_") unless action.include?("/") default_action ||= action.tr("-", "_") unless action.include?("/")
else else
action = nil action = nil

View file

@ -78,7 +78,7 @@ module ActionDispatch
# # Asserts that the generated route gives us our custom route # # Asserts that the generated route gives us our custom route
# assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" } # assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" }
def assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil) def assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil)
if expected_path =~ %r{://} if %r{://}.match?(expected_path)
fail_on(URI::InvalidURIError, message) do fail_on(URI::InvalidURIError, message) do
uri = URI.parse(expected_path) uri = URI.parse(expected_path)
expected_path = uri.path.to_s.empty? ? "/" : uri.path expected_path = uri.path.to_s.empty? ? "/" : uri.path
@ -189,7 +189,7 @@ module ActionDispatch
request = ActionController::TestRequest.create @controller.class request = ActionController::TestRequest.create @controller.class
if path =~ %r{://} if %r{://}.match?(path)
fail_on(URI::InvalidURIError, msg) do fail_on(URI::InvalidURIError, msg) do
uri = URI.parse(path) uri = URI.parse(path)
request.env["rack.url_scheme"] = uri.scheme || "http" request.env["rack.url_scheme"] = uri.scheme || "http"

View file

@ -217,7 +217,7 @@ module ActionDispatch
method = :post method = :post
end end
if path =~ %r{://} if %r{://}.match?(path)
path = build_expanded_path(path) do |location| path = build_expanded_path(path) do |location|
https! URI::HTTPS === location if location.scheme https! URI::HTTPS === location if location.scheme

View file

@ -107,7 +107,7 @@ namespace :assets do
end end
print "[verify] #{file} is a UMD module " print "[verify] #{file} is a UMD module "
if pathname.read =~ /module\.exports.*define\.amd/m if /module\.exports.*define\.amd/m.match?(pathname.read)
puts "[OK]" puts "[OK]"
else else
$stderr.puts "[FAIL]" $stderr.puts "[FAIL]"

View file

@ -15,7 +15,7 @@ module ActionView
def validate_color_string(string) def validate_color_string(string)
regex = /#[0-9a-fA-F]{6}/ regex = /#[0-9a-fA-F]{6}/
if regex.match(string) if regex.match?(string)
string.downcase string.downcase
else else
"#000000" "#000000"

View file

@ -188,7 +188,7 @@ module ActionView
unless separator.empty? unless separator.empty?
text.split(separator).each do |value| text.split(separator).each do |value|
if value.match(regex) if value.match?(regex)
phrase = value phrase = value
break break
end end

View file

@ -81,7 +81,7 @@ module ActiveRecord
alias :in_use? :owner alias :in_use? :owner
def self.type_cast_config_to_integer(config) def self.type_cast_config_to_integer(config)
if config =~ SIMPLE_INT if SIMPLE_INT.match?(config)
config.to_i config.to_i
else else
config config

View file

@ -245,7 +245,7 @@ module ActiveRecord
if distinct && (group_values.any? || select_values.empty? && order_values.empty?) if distinct && (group_values.any? || select_values.empty? && order_values.empty?)
column_name = primary_key column_name = primary_key
end end
elsif column_name =~ /\s*DISTINCT[\s(]+/i elsif /\s*DISTINCT[\s(]+/i.match?(column_name)
distinct = nil distinct = nil
end end
end end

View file

@ -30,7 +30,7 @@ namespace :guides do
unless Kindlerb.kindlegen_available? unless Kindlerb.kindlegen_available?
abort "Please run `setupkindlerb` to install kindlegen" abort "Please run `setupkindlerb` to install kindlegen"
end end
unless `convert` =~ /convert/ unless /convert/.match?(`convert`)
abort "Please install ImageMagick" abort "Please install ImageMagick"
end end
ENV["KINDLE"] = "1" ENV["KINDLE"] = "1"

View file

@ -35,7 +35,7 @@ module Kindle
def generate_front_matter(html_pages) def generate_front_matter(html_pages)
frontmatter = [] frontmatter = []
html_pages.delete_if { |x| html_pages.delete_if { |x|
if x =~ /(toc|welcome|copyright).html/ if /(toc|welcome|copyright).html/.match?(x)
frontmatter << x unless x =~ /toc/ frontmatter << x unless x =~ /toc/
true true
end end

View file

@ -69,7 +69,7 @@ module RailsGuides
end end
def extract_raw_header_and_body def extract_raw_header_and_body
if @raw_body =~ /^\-{40,}$/ if /^\-{40,}$/.match?(@raw_body)
@raw_header, _, @raw_body = @raw_body.partition(/^\-{40,}$/).map(&:strip) @raw_header, _, @raw_body = @raw_body.partition(/^\-{40,}$/).map(&:strip)
end end
end end
@ -89,7 +89,7 @@ module RailsGuides
hierarchy = [] hierarchy = []
doc.children.each do |node| doc.children.each do |node|
if node.name =~ /^h[3-6]$/ if /^h[3-6]$/.match?(node.name)
case node.name case node.name
when "h3" when "h3"
hierarchy = [node] hierarchy = [node]

View file

@ -35,7 +35,7 @@ HTML
def paragraph(text) def paragraph(text)
if text =~ %r{^NOTE:\s+Defined\s+in\s+<code>(.*?)</code>\.?$} if text =~ %r{^NOTE:\s+Defined\s+in\s+<code>(.*?)</code>\.?$}
%(<div class="note"><p>Defined in <code><a href="#{github_file_url($1)}">#{$1}</a></code>.</p></div>) %(<div class="note"><p>Defined in <code><a href="#{github_file_url($1)}">#{$1}</a></code>.</p></div>)
elsif text =~ /^(TIP|IMPORTANT|CAUTION|WARNING|NOTE|INFO|TODO)[.:]/ elsif /^(TIP|IMPORTANT|CAUTION|WARNING|NOTE|INFO|TODO)[.:]/.match?(text)
convert_notes(text) convert_notes(text)
elsif text.include?("DO NOT READ THIS FILE ON GITHUB") elsif text.include?("DO NOT READ THIS FILE ON GITHUB")
elsif text =~ /^\[<sup>(\d+)\]:<\/sup> (.+)$/ elsif text =~ /^\[<sup>(\d+)\]:<\/sup> (.+)$/
@ -110,7 +110,7 @@ HTML
end end
def api_link(url) def api_link(url)
if url =~ %r{http://api\.rubyonrails\.org/v\d+\.} if %r{http://api\.rubyonrails\.org/v\d+\.}.match?(url)
url url
elsif edge elsif edge
url.sub("api", "edgeapi") url.sub("api", "edgeapi")

View file

@ -49,7 +49,7 @@ EOS
if exe = find_executable if exe = find_executable
contents = File.read(exe) contents = File.read(exe)
if contents =~ /(APP|ENGINE)_PATH/ if /(APP|ENGINE)_PATH/.match?(contents)
exec RUBY, exe, *ARGV exec RUBY, exe, *ARGV
break # non reachable, hack to be able to stub exec in the test suite break # non reachable, hack to be able to stub exec in the test suite
elsif exe.end_with?("bin/rails") && contents.include?("This file was generated by Bundler") elsif exe.end_with?("bin/rails") && contents.include?("This file was generated by Bundler")

View file

@ -46,7 +46,7 @@ class CodeStatistics #:nodoc:
if File.directory?(path) && (/^\./ !~ file_name) if File.directory?(path) && (/^\./ !~ file_name)
stats.add(calculate_directory_statistics(path, pattern)) stats.add(calculate_directory_statistics(path, pattern))
elsif file_name =~ pattern elsif file_name&.match?(pattern)
stats.add_by_file_path(path) stats.add_by_file_path(path)
end end
end end

View file

@ -42,7 +42,7 @@ module Rails
rescue Rails::Secrets::MissingKeyError => error rescue Rails::Secrets::MissingKeyError => error
say error.message say error.message
rescue Errno::ENOENT => error rescue Errno::ENOENT => error
if error.message =~ /secrets\.yml\.enc/ if /secrets\.yml\.enc/.match?(error.message)
deprecate_in_favor_of_credentials_and_exit deprecate_in_favor_of_credentials_and_exit
else else
raise raise

View file

@ -376,7 +376,7 @@ module Rails
comment = "See https://github.com/rails/execjs#readme for more supported runtimes" comment = "See https://github.com/rails/execjs#readme for more supported runtimes"
if defined?(JRUBY_VERSION) if defined?(JRUBY_VERSION)
GemfileEntry.version "therubyrhino", nil, comment GemfileEntry.version "therubyrhino", nil, comment
elsif RUBY_PLATFORM =~ /mingw|mswin/ elsif RUBY_PLATFORM.match?(/mingw|mswin/)
GemfileEntry.version "duktape", nil, comment GemfileEntry.version "duktape", nil, comment
else else
GemfileEntry.new "mini_racer", nil, comment, { platforms: :ruby }, true GemfileEntry.new "mini_racer", nil, comment, { platforms: :ruby }, true

View file

@ -515,7 +515,7 @@ module Rails
end end
def valid_const? def valid_const?
if app_const =~ /^\d/ if /^\d/.match?(app_const)
raise Error, "Invalid application name #{original_app_name}. Please give a name which does not start with numbers." raise Error, "Invalid application name #{original_app_name}. Please give a name which does not start with numbers."
elsif RESERVED_NAMES.include?(original_app_name) elsif RESERVED_NAMES.include?(original_app_name)
raise Error, "Invalid application name #{original_app_name}. Please give a " \ raise Error, "Invalid application name #{original_app_name}. Please give a " \

View file

@ -385,11 +385,11 @@ task default: :test
end end
def valid_const? def valid_const?
if original_name =~ /-\d/ if /-\d/.match?(original_name)
raise Error, "Invalid plugin name #{original_name}. Please give a name which does not contain a namespace starting with numeric characters." raise Error, "Invalid plugin name #{original_name}. Please give a name which does not contain a namespace starting with numeric characters."
elsif original_name =~ /[^\w-]+/ elsif /[^\w-]+/.match?(original_name)
raise Error, "Invalid plugin name #{original_name}. Please give a name which uses only alphabetic, numeric, \"_\" or \"-\" characters." raise Error, "Invalid plugin name #{original_name}. Please give a name which uses only alphabetic, numeric, \"_\" or \"-\" characters."
elsif camelized =~ /^\d/ elsif /^\d/.match?(camelized)
raise Error, "Invalid plugin name #{original_name}. Please give a name which does not start with numbers." raise Error, "Invalid plugin name #{original_name}. Please give a name which does not start with numbers."
elsif RESERVED_NAMES.include?(name) elsif RESERVED_NAMES.include?(name)
raise Error, "Invalid plugin name #{original_name}. Please give a " \ raise Error, "Invalid plugin name #{original_name}. Please give a " \

View file

@ -63,7 +63,7 @@ module Rails
# Extract absolute and relative paths but skip -n /.*/ regexp filters. # Extract absolute and relative paths but skip -n /.*/ regexp filters.
argv.select { |arg| arg =~ %r%^/?\w+/% && !arg.end_with?("/") }.map do |path| argv.select { |arg| arg =~ %r%^/?\w+/% && !arg.end_with?("/") }.map do |path|
case case
when path =~ /(:\d+)+$/ when /(:\d+)+$/.match?(path)
file, *lines = path.split(":") file, *lines = path.split(":")
filters << [ file, lines ] filters << [ file, lines ]
file file

View file

@ -89,7 +89,7 @@ npm_version = version.gsub(/\./).with_index { |s, i| i >= 2 ? "-" : s }
if File.exist?("#{framework}/package.json") if File.exist?("#{framework}/package.json")
Dir.chdir("#{framework}") do Dir.chdir("#{framework}") do
npm_tag = version =~ /[a-z]/ ? "pre" : "latest" npm_tag = /[a-z]/.match?(version) ? "pre" : "latest"
sh "npm publish --tag #{npm_tag}" sh "npm publish --tag #{npm_tag}"
end end
end end