Use match? where we don't need MatchData

This commit is contained in:
Akira Matsuda 2019-07-29 14:23:10 +09:00
parent 0d981a2b3d
commit 0196551e60
46 changed files with 67 additions and 67 deletions

View File

@ -91,7 +91,7 @@ class ClientTest < ActionCable::TestCase
rescue RuntimeError => ex rescue RuntimeError => ex
# Work around https://bugs.ruby-lang.org/issues/13239 # Work around https://bugs.ruby-lang.org/issues/13239
raise unless ex.message =~ /can't modify frozen IOError/ raise unless ex.message.match?(/can't modify frozen IOError/)
# Handle this as if it were the IOError: do the same as above. # Handle this as if it were the IOError: do the same as above.
server.binder.close server.binder.close

View File

@ -482,7 +482,7 @@ module ActionController
def raw_params(auth) def raw_params(auth)
_raw_params = auth.sub(TOKEN_REGEX, "").split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/) _raw_params = auth.sub(TOKEN_REGEX, "").split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
if !(_raw_params.first =~ %r{\A#{TOKEN_KEY}}) if !(%r{\A#{TOKEN_KEY}}.match?(_raw_params.first))
_raw_params[0] = "#{TOKEN_KEY}#{_raw_params.first}" _raw_params[0] = "#{TOKEN_KEY}#{_raw_params.first}"
end end

View File

@ -142,7 +142,7 @@ module ActionController #:nodoc:
# #
# You can set the variant in a +before_action+: # You can set the variant in a +before_action+:
# #
# request.variant = :tablet if request.user_agent =~ /iPad/ # request.variant = :tablet if /iPad/.match?(request.user_agent)
# #
# Respond to variants in the action just like you respond to formats: # Respond to variants in the action just like you respond to formats:
# #

View File

@ -280,7 +280,7 @@ module ActionController #:nodoc:
# Check for cross-origin JavaScript responses. # Check for cross-origin JavaScript responses.
def non_xhr_javascript_response? # :doc: def non_xhr_javascript_response? # :doc:
content_type =~ %r(\A(?:text|application)/javascript) && !request.xhr? %r(\A(?:text|application)/javascript).match?(content_type) && !request.xhr?
end end
AUTHENTICITY_TOKEN_LENGTH = 32 AUTHENTICITY_TOKEN_LENGTH = 32

View File

@ -225,7 +225,7 @@ module ActionController
class << self class << self
def nested_attribute?(key, value) # :nodoc: def nested_attribute?(key, value) # :nodoc:
key =~ /\A-?\d+\z/ && (value.is_a?(Hash) || value.is_a?(Parameters)) /\A-?\d+\z/.match?(key) && (value.is_a?(Hash) || value.is_a?(Parameters))
end end
end end

View File

@ -593,8 +593,8 @@ module ActionController
private private
def scrub_env!(env) def scrub_env!(env)
env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ } env.delete_if { |k, v| k.match?(/^(action_dispatch|rack)\.request/) }
env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ } env.delete_if { |k, v| k.match?(/^action_dispatch\.rescue/) }
env.delete "action_dispatch.request.query_parameters" env.delete "action_dispatch.request.query_parameters"
env.delete "action_dispatch.request.request_parameters" env.delete "action_dispatch.request.request_parameters"
env["rack.input"] = StringIO.new env["rack.input"] = StringIO.new

View File

@ -33,7 +33,7 @@ module ActionDispatch #:nodoc:
private private
def html_response?(headers) def html_response?(headers)
if content_type = headers[CONTENT_TYPE] if content_type = headers[CONTENT_TYPE]
content_type =~ /html/ /html/.match?(content_type)
end end
end end

View File

@ -33,7 +33,7 @@ module ActionDispatch #:nodoc:
private private
def html_response?(headers) def html_response?(headers)
if content_type = headers[CONTENT_TYPE] if content_type = headers[CONTENT_TYPE]
content_type =~ /html/ /html/.match?(content_type)
end end
end end

View File

@ -23,7 +23,7 @@ module ActionDispatch
# change { file: { code: "xxxx"} } # change { file: { code: "xxxx"} }
# #
# env["action_dispatch.parameter_filter"] = -> (k, v) do # env["action_dispatch.parameter_filter"] = -> (k, v) do
# v.reverse! if k =~ /secret/i # v.reverse! if k.match?(/secret/i)
# end # end
# => reverses the value to all keys matching /secret/i # => reverses the value to all keys matching /secret/i
module FilterParameters module FilterParameters

View File

@ -27,7 +27,7 @@ module ActionDispatch
if String === filter if String === filter
location.include?(filter) location.include?(filter)
elsif Regexp === filter elsif Regexp === filter
location =~ filter location.match?(filter)
end end
end end
end end

View File

@ -290,7 +290,7 @@ module Mime
end end
def html? def html?
symbol == :html || @string =~ /html/ (symbol == :html) || /html/.match?(@string)
end end
def all?; false; end def all?; false; end

View File

@ -265,7 +265,7 @@ module ActionDispatch
# (case-insensitive), which may need to be manually added depending on the # (case-insensitive), which may need to be manually added depending on the
# choice of JavaScript libraries and frameworks. # choice of JavaScript libraries and frameworks.
def xml_http_request? def xml_http_request?
get_header("HTTP_X_REQUESTED_WITH") =~ /XMLHttpRequest/i /XMLHttpRequest/i.match?(get_header("HTTP_X_REQUESTED_WITH"))
end end
alias :xhr? :xml_http_request? alias :xhr? :xml_http_request?
@ -400,7 +400,7 @@ module ActionDispatch
# True if the request came from localhost, 127.0.0.1, or ::1. # True if the request came from localhost, 127.0.0.1, or ::1.
def local? def local?
LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip LOCALHOST.match?(remote_addr) && LOCALHOST.match?(remote_ip)
end end
def request_parameters=(params) def request_parameters=(params)

View File

@ -13,7 +13,7 @@ module ActionDispatch
# #
# Requests can opt-out of redirection with +exclude+: # Requests can opt-out of redirection with +exclude+:
# #
# config.ssl_options = { redirect: { exclude: -> request { request.path =~ /healthcheck/ } } } # config.ssl_options = { redirect: { exclude: -> request { /healthcheck/.match?(request.path) } } }
# #
# Cookies will not be flagged as secure for excluded requests. # Cookies will not be flagged as secure for excluded requests.
# #

View File

@ -83,11 +83,11 @@ module ActionDispatch
end end
def gzip_encoding_accepted?(request) def gzip_encoding_accepted?(request)
request.accept_encoding.any? { |enc, quality| enc =~ /\bgzip\b/i } request.accept_encoding.any? { |enc, quality| /\bgzip\b/i.match?(enc) }
end end
def gzip_file_path(path) def gzip_file_path(path)
can_gzip_mime = content_type(path) =~ /\A(?:text\/|application\/javascript)/ can_gzip_mime = /\A(?:text\/|application\/javascript)/.match?(content_type(path))
gzip_path = "#{path}.gz" gzip_path = "#{path}.gz"
if can_gzip_mime && File.exist?(File.join(@root, ::Rack::Utils.unescape_path(gzip_path))) if can_gzip_mime && File.exist?(File.join(@root, ::Rack::Utils.unescape_path(gzip_path)))
gzip_path gzip_path

View File

@ -94,7 +94,7 @@ module ActionDispatch
if filter if filter
@routes.select do |route| @routes.select do |route|
route_wrapper = RouteWrapper.new(route) route_wrapper = RouteWrapper.new(route)
filter.any? { |default, value| route_wrapper.send(default) =~ value } filter.any? { |default, value| value.match?(route_wrapper.send(default)) }
end end
else else
@routes @routes

View File

@ -367,7 +367,7 @@ module ActionDispatch
def translate_controller(controller) def translate_controller(controller)
return controller if Regexp === controller return controller if Regexp === controller
return controller.to_s if controller =~ /\A[a-z_0-9][a-z_0-9\/]*\z/ return controller.to_s if /\A[a-z_0-9][a-z_0-9\/]*\z/.match?(controller)
yield yield
end end
@ -403,7 +403,7 @@ module ActionDispatch
# for root cases, where the latter is the correct one. # for root cases, where the latter is the correct one.
def self.normalize_path(path) def self.normalize_path(path)
path = Journey::Router::Utils.normalize_path(path) path = Journey::Router::Utils.normalize_path(path)
path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/(\(+[^)]+\)){1,}$} path.gsub!(%r{/(\(+)/?}, '\1/') unless %r{^/(\(+[^)]+\)){1,}$}.match?(path)
path path
end end
@ -996,7 +996,7 @@ module ActionDispatch
# #
# Requests to routes can be constrained based on specific criteria: # Requests to routes can be constrained based on specific criteria:
# #
# constraints(-> (req) { req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do # constraints(-> (req) { /iPhone/.match?(req.env["HTTP_USER_AGENT"]) }) do
# resources :iphones # resources :iphones
# end # end
# #
@ -1006,7 +1006,7 @@ module ActionDispatch
# #
# class Iphone # class Iphone
# def self.matches?(request) # def self.matches?(request)
# request.env["HTTP_USER_AGENT"] =~ /iPhone/ # /iPhone/.match?(request.env["HTTP_USER_AGENT"])
# end # end
# end # end
# #
@ -1916,7 +1916,7 @@ module ActionDispatch
end end
def using_match_shorthand?(path) def using_match_shorthand?(path)
path =~ %r{^/?[-\w]+/[-\w/]+$} %r{^/?[-\w]+/[-\w/]+$}.match?(path)
end end
def decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) def decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints)

View File

@ -836,7 +836,7 @@ module ActionDispatch
def recognize_path(path, environment = {}) def recognize_path(path, environment = {})
method = (environment[:method] || "GET").to_s.upcase method = (environment[:method] || "GET").to_s.upcase
path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://} path = Journey::Router::Utils.normalize_path(path) unless %r{://}.match?(path)
extras = environment[:extras] || {} extras = environment[:extras] || {}
begin begin

View File

@ -606,7 +606,7 @@ class MetalIntegrationTest < ActionDispatch::IntegrationTest
class Poller class Poller
def self.call(env) def self.call(env)
if env["PATH_INFO"] =~ /^\/success/ if /^\/success/.match?(env["PATH_INFO"])
[200, { "Content-Type" => "text/plain", "Content-Length" => "12" }, ["Hello World!"]] [200, { "Content-Type" => "text/plain", "Content-Length" => "12" }, ["Hello World!"]]
else else
[404, { "Content-Type" => "text/plain", "Content-Length" => "0" }, []] [404, { "Content-Type" => "text/plain", "Content-Length" => "0" }, []]

View File

@ -139,7 +139,7 @@ class ACLogSubscriberTest < ActionController::TestCase
def test_process_action_without_parameters def test_process_action_without_parameters
get :show get :show
wait wait
assert_nil logs.detect { |l| l =~ /Parameters/ } assert_nil logs.detect { |l| /Parameters/.match?(l) }
end end
def test_process_action_with_parameters def test_process_action_with_parameters

View File

@ -68,7 +68,7 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
post "/parse", params: json, headers: { "CONTENT_TYPE" => "application/json", "action_dispatch.show_exceptions" => true, "action_dispatch.logger" => ActiveSupport::Logger.new(output) } post "/parse", params: json, headers: { "CONTENT_TYPE" => "application/json", "action_dispatch.show_exceptions" => true, "action_dispatch.logger" => ActiveSupport::Logger.new(output) }
assert_response :bad_request assert_response :bad_request
output.rewind && err = output.read output.rewind && err = output.read
assert err =~ /Error occurred while parsing request parameters/ assert err.match?(/Error occurred while parsing request parameters/)
end end
end end

View File

@ -12,7 +12,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
class IpRestrictor class IpRestrictor
def self.matches?(request) def self.matches?(request)
request.ip =~ /192\.168\.1\.1\d\d/ /192\.168\.1\.1\d\d/.match?(request.ip)
end end
end end
@ -3823,7 +3823,7 @@ private
end end
def method_missing(method, *args, &block) def method_missing(method, *args, &block)
if method.to_s =~ /_(path|url)$/ if method.to_s.match?(/_(path|url)$/)
@app.routes.url_helpers.send(method, *args, &block) @app.routes.url_helpers.send(method, *args, &block)
else else
super super
@ -5137,7 +5137,7 @@ class TestRecognizePath < ActionDispatch::IntegrationTest
end end
def matches?(request) def matches?(request)
request.path_parameters[key] =~ pattern pattern.match?(request.path_parameters[key])
end end
end end
@ -5147,8 +5147,8 @@ class TestRecognizePath < ActionDispatch::IntegrationTest
get "/hash/:foo", to: "pages#show", constraints: { foo: /foo/ } get "/hash/:foo", to: "pages#show", constraints: { foo: /foo/ }
get "/hash/:bar", to: "pages#show", constraints: { bar: /bar/ } get "/hash/:bar", to: "pages#show", constraints: { bar: /bar/ }
get "/proc/:foo", to: "pages#show", constraints: proc { |r| r.path_parameters[:foo] =~ /foo/ } get "/proc/:foo", to: "pages#show", constraints: proc { |r| /foo/.match?(r.path_parameters[:foo]) }
get "/proc/:bar", to: "pages#show", constraints: proc { |r| r.path_parameters[:bar] =~ /bar/ } get "/proc/:bar", to: "pages#show", constraints: proc { |r| /bar/.match?(r.path_parameters[:bar]) }
get "/class/:foo", to: "pages#show", constraints: PageConstraint.new(:foo, /foo/) get "/class/:foo", to: "pages#show", constraints: PageConstraint.new(:foo, /foo/)
get "/class/:bar", to: "pages#show", constraints: PageConstraint.new(:bar, /bar/) get "/class/:bar", to: "pages#show", constraints: PageConstraint.new(:bar, /bar/)

View File

@ -42,7 +42,7 @@ class RedirectSSLTest < SSLTest
end end
test "exclude can avoid redirect" do test "exclude can avoid redirect" do
excluding = { exclude: -> request { request.path =~ /healthcheck/ } } excluding = { exclude: -> request { request.path.match?(/healthcheck/) } }
assert_not_redirected "http://example.org/healthcheck", redirect: excluding assert_not_redirected "http://example.org/healthcheck", redirect: excluding
assert_redirected from: "http://example.org/", redirect: excluding assert_redirected from: "http://example.org/", redirect: excluding
@ -209,7 +209,7 @@ class SecureCookiesTest < SSLTest
end end
def test_cookies_as_not_secure_with_exclude def test_cookies_as_not_secure_with_exclude
excluding = { exclude: -> request { request.domain =~ /example/ } } excluding = { exclude: -> request { /example/.match?(request.domain) } }
get headers: { "Set-Cookie" => DEFAULT }, ssl_options: { redirect: excluding } get headers: { "Set-Cookie" => DEFAULT }, ssl_options: { redirect: excluding }
assert_cookies(*DEFAULT.split("\n")) assert_cookies(*DEFAULT.split("\n"))

View File

@ -14,7 +14,7 @@ module ActionText
private private
def content_type_is_image?(content_type) def content_type_is_image?(content_type)
content_type.to_s =~ /^image(\/.+|$)/ content_type.to_s.match?(/^image(\/.+|$)/)
end end
def attributes_from_node(node) def attributes_from_node(node)

View File

@ -23,7 +23,7 @@ module ActionText
Fragment.wrap(content).find_all(SELECTOR).select do |node| Fragment.wrap(content).find_all(SELECTOR).select do |node|
node.children.all? do |child| node.children.all? do |child|
if child.text? if child.text?
child.text =~ /\A(\n|\ )*\z/ /\A(\n|\ )*\z/.match?(child.text)
else else
child.matches? ATTACHMENT_SELECTOR child.matches? ATTACHMENT_SELECTOR
end end

View File

@ -228,7 +228,7 @@ module ActionView
# pluralize(2, 'Person', locale: :de) # pluralize(2, 'Person', locale: :de)
# # => 2 Personen # # => 2 Personen
def pluralize(count, singular, plural_arg = nil, plural: plural_arg, locale: I18n.locale) def pluralize(count, singular, plural_arg = nil, plural: plural_arg, locale: I18n.locale)
word = if count == 1 || count.to_s =~ /^1(\.0+)?$/ word = if count == 1 || count.to_s.match?(/^1(\.0+)?$/)
singular singular
else else
plural || singular.pluralize(locale) plural || singular.pluralize(locale)

View File

@ -27,7 +27,7 @@ module ActiveModel
# class EmailValidator < ActiveModel::EachValidator # class EmailValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value) # def validate_each(record, attribute, value)
# record.errors.add attribute, (options[:message] || "is not an email") unless # record.errors.add attribute, (options[:message] || "is not an email") unless
# value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i # /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i.match?(value)
# end # end
# end # end
# #
@ -47,7 +47,7 @@ module ActiveModel
# #
# class TitleValidator < ActiveModel::EachValidator # class TitleValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value) # def validate_each(record, attribute, value)
# record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i # record.errors.add attribute, "must start with 'the'" unless /\Athe/i.match?(value)
# end # end
# end # end
# #

View File

@ -100,7 +100,7 @@ module ActiveRecord
# converting them into an array and iterating through them using # converting them into an array and iterating through them using
# Array#select. # Array#select.
# #
# person.pets.select { |pet| pet.name =~ /oo/ } # person.pets.select { |pet| /oo/.match?(pet.name) }
# # => [ # # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>, # # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>

View File

@ -14,7 +14,7 @@ module Arel
}.grep(Class).each do |klass| }.grep(Class).each do |klass|
next if Nodes::SqlLiteral == klass next if Nodes::SqlLiteral == klass
next if Nodes::BindParam == klass next if Nodes::BindParam == klass
next if klass.name =~ /^Arel::Nodes::(?:Test|.*Test$)/ next if /^Arel::Nodes::(?:Test|.*Test$)/.match?(klass.name)
assert klass.ancestors.include?(Nodes::Node), klass.name assert klass.ancestors.include?(Nodes::Node), klass.name
end end
end end

View File

@ -67,7 +67,7 @@ class FixturesTest < ActiveRecord::TestCase
end end
def call(_, _, _, _, values) def call(_, _, _, _, values)
@events << values[:sql] if values[:sql] =~ /INSERT/ @events << values[:sql] if /INSERT/.match?(values[:sql])
end end
end end

View File

@ -16,7 +16,7 @@ module ActiveSupport
# #
# bc = ActiveSupport::BacktraceCleaner.new # bc = ActiveSupport::BacktraceCleaner.new
# bc.add_filter { |line| line.gsub(Rails.root.to_s, '') } # strip the Rails.root prefix # bc.add_filter { |line| line.gsub(Rails.root.to_s, '') } # strip the Rails.root prefix
# bc.add_silencer { |line| line =~ /puma|rubygems/ } # skip any lines from puma or rubygems # bc.add_silencer { |line| /puma|rubygems/.match?(line) } # skip any lines from puma or rubygems
# bc.clean(exception.backtrace) # perform the cleanup # bc.clean(exception.backtrace) # perform the cleanup
# #
# To reconfigure an existing BacktraceCleaner (like the default one in Rails) # To reconfigure an existing BacktraceCleaner (like the default one in Rails)
@ -65,7 +65,7 @@ module ActiveSupport
# for a given line, it will be excluded from the clean backtrace. # for a given line, it will be excluded from the clean backtrace.
# #
# # Will reject all lines that include the word "puma", like "/gems/puma/server.rb" or "/app/my_puma_server/rb" # # Will reject all lines that include the word "puma", like "/gems/puma/server.rb" or "/app/my_puma_server/rb"
# backtrace_cleaner.add_silencer { |line| line =~ /puma/ } # backtrace_cleaner.add_silencer { |line| /puma/.match?(line) }
def add_silencer(&block) def add_silencer(&block)
@silencers << block @silencers << block
end end

View File

@ -22,7 +22,7 @@ module ActiveSupport
# change { file: { code: "xxxx"} } # change { file: { code: "xxxx"} }
# #
# ActiveSupport::ParameterFilter.new([-> (k, v) do # ActiveSupport::ParameterFilter.new([-> (k, v) do
# v.reverse! if k =~ /secret/i # v.reverse! if /secret/i.match?(k)
# end]) # end])
# => reverses the value to all keys matching /secret/i # => reverses the value to all keys matching /secret/i
class ParameterFilter class ParameterFilter

View File

@ -9,7 +9,7 @@ require "dalli"
# connection pool testing. # connection pool testing.
class SlowDalliClient < Dalli::Client class SlowDalliClient < Dalli::Client
def get(key, options = {}) def get(key, options = {})
if key =~ /latency/ if /latency/.match?(key)
sleep 3 sleep 3
else else
super super

View File

@ -15,7 +15,7 @@ Redis::Connection.drivers.append(driver)
# connection pool testing. # connection pool testing.
class SlowRedis < Redis class SlowRedis < Redis
def get(key, options = {}) def get(key, options = {})
if key =~ /latency/ if /latency/.match?(key)
sleep 3 sleep 3
else else
super super

View File

@ -256,7 +256,7 @@ module CallbacksTest
end end
def respond_to_missing?(sym) def respond_to_missing?(sym)
sym =~ /^(log|wrap)_/ || super sym.match?(/^(log|wrap)_/) || super
end end
end end

View File

@ -22,7 +22,7 @@ class ParameterFilterTest < ActiveSupport::TestCase
filter_words << "blah" filter_words << "blah"
filter_words << lambda { |key, value| filter_words << lambda { |key, value|
value.reverse! if key =~ /bargain/ value.reverse! if /bargain/.match?(key)
} }
filter_words << lambda { |key, value, original_params| filter_words << lambda { |key, value, original_params|
value.replace("world!") if original_params["barg"]["blah"] == "bar" && key == "hello" value.replace("world!") if original_params["barg"]["blah"] == "bar" && key == "hello"
@ -61,7 +61,7 @@ class ParameterFilterTest < ActiveSupport::TestCase
filter_words << "blah" filter_words << "blah"
filter_words << lambda { |key, value| filter_words << lambda { |key, value|
value.reverse! if key =~ /bargain/ value.reverse! if /bargain/.match?(key)
} }
filter_words << lambda { |key, value, original_params| filter_words << lambda { |key, value, original_params|
value.replace("world!") if original_params["barg"]["blah"] == "bar" && key == "hello" value.replace("world!") if original_params["barg"]["blah"] == "bar" && key == "hello"

View File

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

View File

@ -58,19 +58,19 @@ class CodeStatisticsCalculator #:nodoc:
@lines += 1 @lines += 1
if comment_started if comment_started
if patterns[:end_block_comment] && line =~ patterns[:end_block_comment] if patterns[:end_block_comment] && patterns[:end_block_comment].match?(line)
comment_started = false comment_started = false
end end
next next
else else
if patterns[:begin_block_comment] && line =~ patterns[:begin_block_comment] if patterns[:begin_block_comment] && patterns[:begin_block_comment].match?(line)
comment_started = true comment_started = true
next next
end end
end end
@classes += 1 if patterns[:class] && line =~ patterns[:class] @classes += 1 if patterns[:class] && patterns[:class].match?(line)
@methods += 1 if patterns[:method] && line =~ patterns[:method] @methods += 1 if patterns[:method] && patterns[:method].match?(line)
if !line.match?(/^\s*$/) && (patterns[:line_comment].nil? || !line.match?(patterns[:line_comment])) if !line.match?(/^\s*$/) && (patterns[:line_comment].nil? || !line.match?(patterns[:line_comment]))
@code_lines += 1 @code_lines += 1
end end

View File

@ -44,7 +44,7 @@ module Rails
require path require path
return return
rescue LoadError => e rescue LoadError => e
raise unless e.message =~ /#{Regexp.escape(path)}$/ raise unless /#{Regexp.escape(path)}$/.match?(e.message)
rescue Exception => e rescue Exception => e
warn "[WARNING] Could not load #{command_type} #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}" warn "[WARNING] Could not load #{command_type} #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}"
end end

View File

@ -28,7 +28,7 @@ module Rails
if available_environments.include? env if available_environments.include? env
env env
else else
%w( production development test ).detect { |e| e =~ /^#{env}/ } || env %w( production development test ).detect { |e| /^#{env}/.match?(e) } || env
end end
end end

View File

@ -400,7 +400,7 @@ module Rails
end end
def os_supports_listen_out_of_the_box? def os_supports_listen_out_of_the_box?
RbConfig::CONFIG["host_os"] =~ /darwin|linux/ /darwin|linux/.match?(RbConfig::CONFIG["host_os"])
end end
def run_bundle def run_bundle

View File

@ -131,7 +131,7 @@ module Rails
end end
def foreign_key? def foreign_key?
!!(name =~ /_id$/) /_id$/.match?(name)
end end
def reference? def reference?

View File

@ -61,7 +61,7 @@ module Rails
private private
def extract_filters(argv) def extract_filters(argv)
# 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| %r%^/?\w+/%.match?(arg) && !arg.end_with?("/") }.map do |path|
case case
when /(:\d+)+$/.match?(path) when /(:\d+)+$/.match?(path)
file, *lines = path.split(":") file, *lines = path.split(":")

View File

@ -311,7 +311,7 @@ module ApplicationTests
manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first
assets = ActiveSupport::JSON.decode(File.read(manifest)) assets = ActiveSupport::JSON.decode(File.read(manifest))
assert asset_path = assets["assets"].find { |(k, _)| k && k =~ /.png/ }[1] assert asset_path = assets["assets"].find { |(k, _)| /.png/.match?(k) }[1]
# Load app env # Load app env
app "development" app "development"

View File

@ -456,7 +456,7 @@ module ApplicationTests
test "filter_parameters should be able to set via config.filter_parameters" do test "filter_parameters should be able to set via config.filter_parameters" do
add_to_config <<-RUBY add_to_config <<-RUBY
config.filter_parameters += [ :foo, 'bar', lambda { |key, value| config.filter_parameters += [ :foo, 'bar', lambda { |key, value|
value = value.reverse if key =~ /baz/ value = value.reverse if /baz/.match?(key)
}] }]
RUBY RUBY
@ -790,7 +790,7 @@ module ApplicationTests
end end
get "/" get "/"
assert last_response.body =~ /csrf\-param/ assert /csrf\-param/.match?(last_response.body)
end end
test "default form builder specified as a string" do test "default form builder specified as a string" do

View File

@ -678,7 +678,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_inclusion_of_listen_related_configuration_by_default def test_inclusion_of_listen_related_configuration_by_default
run_generator run_generator
if RbConfig::CONFIG["host_os"] =~ /darwin|linux/ if /darwin|linux/.match?(RbConfig::CONFIG["host_os"])
assert_listen_related_configuration assert_listen_related_configuration
else else
assert_no_listen_related_configuration assert_no_listen_related_configuration
@ -690,7 +690,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
Object.const_set(:RUBY_ENGINE, "MyRuby") Object.const_set(:RUBY_ENGINE, "MyRuby")
run_generator run_generator
if RbConfig::CONFIG["host_os"] =~ /darwin|linux/ if /darwin|linux/.match?(RbConfig::CONFIG["host_os"])
assert_listen_related_configuration assert_listen_related_configuration
else else
assert_no_listen_related_configuration assert_no_listen_related_configuration
@ -708,7 +708,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_evented_file_update_checker_config def test_evented_file_update_checker_config
run_generator run_generator
assert_file "config/environments/development.rb" do |content| assert_file "config/environments/development.rb" do |content|
if RbConfig::CONFIG["host_os"] =~ /darwin|linux/ if /darwin|linux/.match?(RbConfig::CONFIG["host_os"])
assert_match(/^\s*config\.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) assert_match(/^\s*config\.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content)
else else
assert_match(/^\s*# config\.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) assert_match(/^\s*# config\.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content)

View File

@ -110,7 +110,7 @@ module RailtiesTest
assert_no_match(/\d+_create_users/, output.join("\n")) assert_no_match(/\d+_create_users/, output.join("\n"))
bukkits_migration_order = output.index(output.detect { |o| /NOTE: Migration \d+_create_sessions\.rb from bukkits has been skipped/ =~ o }) bukkits_migration_order = output.index(output.detect { |o| /NOTE: Migration \d+_create_sessions\.rb from bukkits has been skipped/.match?(o) })
assert_not_nil bukkits_migration_order, "Expected migration to be skipped" assert_not_nil bukkits_migration_order, "Expected migration to be skipped"
end end
end end