Skip to content

Freeze string literals when not mutated. #20946

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 19, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion actionpack/lib/abstract_controller/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def clear_action_methods!
# ==== Returns
# * <tt>String</tt>
def controller_path
@controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
@controller_path ||= name.sub(/Controller$/, ''.freeze).underscore unless anonymous?
end

# Refresh the cached action_methods when a new action_method is added.
Expand Down
2 changes: 1 addition & 1 deletion actionpack/lib/abstract_controller/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def add_template_helper(mod)
end

def default_helper_module!
module_name = name.sub(/Controller$/, '')
module_name = name.sub(/Controller$/, ''.freeze)
module_path = module_name.underscore
helper module_path
rescue LoadError => e
Expand Down
2 changes: 1 addition & 1 deletion actionpack/lib/action_controller/log_subscriber.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def process_action(event)
status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
end
message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{event.duration.round}ms"
message << " (#{additions.join(" | ")})" unless additions.blank?
message << " (#{additions.join(" | ".freeze)})" unless additions.blank?
message
end
end
Expand Down
4 changes: 2 additions & 2 deletions actionpack/lib/action_controller/metal/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def helper_attr(*attrs)

# Provides a proxy to access helpers methods from outside the view.
def helpers
@helper_proxy ||= begin
@helper_proxy ||= begin
proxy = ActionView::Base.new
proxy.config = config.inheritable_copy
proxy.extend(_helpers)
Expand All @@ -100,7 +100,7 @@ def modules_for_helpers(args)
def all_helpers_from_path(path)
helpers = Array(path).flat_map do |_path|
extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1'.freeze) }
names.sort!
end
helpers.uniq!
Expand Down
8 changes: 4 additions & 4 deletions actionpack/lib/action_dispatch/http/parameter_filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ def self.compile(filters)
end
end

deep_regexps, regexps = regexps.partition { |r| r.to_s.include?("\\.") }
deep_strings, strings = strings.partition { |s| s.include?("\\.") }
deep_regexps, regexps = regexps.partition { |r| r.to_s.include?("\\.".freeze) }
deep_strings, strings = strings.partition { |s| s.include?("\\.".freeze) }

regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
deep_regexps << Regexp.new(deep_strings.join('|'), true) unless deep_strings.empty?
regexps << Regexp.new(strings.join('|'.freeze), true) unless strings.empty?
deep_regexps << Regexp.new(deep_strings.join('|'.freeze), true) unless deep_strings.empty?

new regexps, deep_regexps, blocks
end
Expand Down
2 changes: 1 addition & 1 deletion actionpack/lib/action_dispatch/http/url.rb
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ def raw_host_with_port
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.host # => "example.com"
def host
raw_host_with_port.sub(/:\d+$/, '')
raw_host_with_port.sub(/:\d+$/, ''.freeze)
end

# Returns a \host:\port string for this request, such as "example.com" or
Expand Down
2 changes: 1 addition & 1 deletion actionpack/lib/action_dispatch/journey/nodes/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def to_sym
end

def name
left.tr '*:', ''
left.tr '*:'.freeze, ''.freeze
end

def type
Expand Down
6 changes: 3 additions & 3 deletions actionpack/lib/action_dispatch/journey/router/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ class Utils # :nodoc:
# normalize_path("/%ab") # => "/%AB"
def self.normalize_path(path)
path = "/#{path}"
path.squeeze!('/')
path.sub!(%r{/+\Z}, '')
path.squeeze!('/'.freeze)
path.sub!(%r{/+\Z}, ''.freeze)
path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
path = '/' if path == ''
path = '/' if path == ''.freeze
path
end

Expand Down
6 changes: 3 additions & 3 deletions actionpack/lib/action_dispatch/middleware/static.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def match?(path)
paths = [path, "#{path}#{ext}", "#{path}/#{@index}#{ext}"]

if match = paths.detect { |p|
path = File.join(@root, p.force_encoding('UTF-8'))
path = File.join(@root, p.force_encoding('UTF-8'.freeze))
begin
File.file?(path) && File.readable?(path)
rescue SystemCallError
Expand Down Expand Up @@ -76,7 +76,7 @@ def ext
end

def content_type(path)
::Rack::Mime.mime_type(::File.extname(path), 'text/plain')
::Rack::Mime.mime_type(::File.extname(path), 'text/plain'.freeze)
end

def gzip_encoding_accepted?(env)
Expand Down Expand Up @@ -112,7 +112,7 @@ def initialize(app, path, cache_control = nil, index: 'index')
def call(env)
case env['REQUEST_METHOD']
when 'GET', 'HEAD'
path = env['PATH_INFO'].chomp('/')
path = env['PATH_INFO'].chomp('/'.freeze)
if match = @file_handler.match?(path)
env['PATH_INFO'] = match
return @file_handler.call(env)
Expand Down
2 changes: 1 addition & 1 deletion actionpack/lib/action_dispatch/routing/route_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,7 @@ def use_relative_controller!

# Remove leading slashes from controllers
def normalize_controller!
@options[:controller] = controller.sub(%r{^/}, '') if controller
@options[:controller] = controller.sub(%r{^/}, ''.freeze) if controller
end

# Move 'index' action from options to recall
Expand Down
2 changes: 1 addition & 1 deletion actionview/lib/action_view/helpers/asset_tag_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def image_tag(source, options={})
# image_alt('underscored_file_name.png')
# # => Underscored file name
def image_alt(src)
File.basename(src, '.*').sub(/-[[:xdigit:]]{32}\z/, '').tr('-_', ' ').capitalize
File.basename(src, '.*'.freeze).sub(/-[[:xdigit:]]{32}\z/, ''.freeze).tr('-_'.freeze, ' '.freeze).capitalize
end

# Returns an HTML video tag for the +sources+. If +sources+ is a string,
Expand Down
2 changes: 1 addition & 1 deletion actionview/lib/action_view/helpers/asset_url_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def asset_path(source, options = {})
return "" unless source.present?
return source if source =~ URI_REGEXP

tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, '')
tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, ''.freeze)

if extname = compute_asset_extname(source, options)
source = "#{source}#{extname}"
Expand Down
6 changes: 3 additions & 3 deletions actionview/lib/action_view/lookup_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -173,13 +173,13 @@ def detail_args_for(options)
# name instead of the prefix.
def normalize_name(name, prefixes) #:nodoc:
prefixes = prefixes.presence
parts = name.to_s.split('/')
parts = name.to_s.split('/'.freeze)
parts.shift if parts.first.empty?
name = parts.pop

return name, prefixes || [""] if parts.empty?

parts = parts.join('/')
parts = parts.join('/'.freeze)
prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]

return name, prefixes
Expand All @@ -204,7 +204,7 @@ def initialize(view_paths, details = {}, prefixes = [])
# add :html as fallback to :js.
def formats=(values)
if values
values.concat(default_formats) if values.delete "*/*"
values.concat(default_formats) if values.delete "*/*".freeze
if values == [:js]
values << :html
@html_fallback_for_js = true
Expand Down
8 changes: 4 additions & 4 deletions actionview/lib/action_view/template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def refresh(view)
end

def inspect
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", ''.freeze) : identifier
end

# This method is responsible for properly setting the encoding of the
Expand Down Expand Up @@ -337,13 +337,13 @@ def locals_code #:nodoc:
def method_name #:nodoc:
@method_name ||= begin
m = "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}"
m.tr!('-', '_')
m.tr!('-'.freeze, '_'.freeze)
m
end
end

def identifier_method_name #:nodoc:
inspect.tr('^a-z_', '_')
inspect.tr('^a-z_'.freeze, '_'.freeze)
end

def instrument(action, &block)
Expand All @@ -366,7 +366,7 @@ def resource_cache_call_match
end

def inferred_cache_name
@inferred_cache_name ||= @virtual_path.split('/').last.sub('_', '')
@inferred_cache_name ||= @virtual_path.split('/'.freeze).last.sub('_'.freeze, ''.freeze)
end
end
end
4 changes: 2 additions & 2 deletions actionview/lib/action_view/template/resolver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def build_query(path, details)
end

def escape_entry(entry)
entry.gsub(/[*?{}\[\]]/, '\\\\\\&')
entry.gsub(/[*?{}\[\]]/, '\\\\\\&'.freeze)
end

# Returns the file mtime from the filesystem.
Expand All @@ -234,7 +234,7 @@ def mtime(p)
# from the path, or the handler, we should return the array of formats given
# to the resolver.
def extract_handler_and_format_and_variant(path, default_formats)
pieces = File.basename(path).split('.')
pieces = File.basename(path).split('.'.freeze)
pieces.shift

extension = pieces.pop
Expand Down
2 changes: 1 addition & 1 deletion activemodel/lib/active_model/attribute_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ def define_proxy_call(include_private, mod, name, send, *extra) #:nodoc:
"define_method(:'#{name}') do |*args|"
end

extra = (extra.map!(&:inspect) << "*args").join(", ")
extra = (extra.map!(&:inspect) << "*args").join(", ".freeze)

target = if send =~ CALL_COMPILABLE_REGEXP
"#{"self." unless include_private}#{send}(#{extra})"
Expand Down
2 changes: 1 addition & 1 deletion activemodel/lib/active_model/naming.rb
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def human(options={})
private

def _singularize(string)
ActiveSupport::Inflector.underscore(string).tr('/', '_')
ActiveSupport::Inflector.underscore(string).tr('/'.freeze, '_'.freeze)
end
end

Expand Down
2 changes: 1 addition & 1 deletion activemodel/lib/active_model/validations/validates.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def validates(*attributes)
key = "#{key.to_s.camelize}Validator"

begin
validator = key.include?('::') ? key.constantize : const_get(key)
validator = key.include?('::'.freeze) ? key.constantize : const_get(key)
rescue NameError
raise ArgumentError, "Unknown validator: '#{key}'"
end
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/attribute_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def initialize

def [](name)
@method_cache.compute_if_absent(name) do
safe_name = name.unpack('h*').first
safe_name = name.unpack('h*'.freeze).first
temp_method = "__temp__#{safe_name}"
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
@module.module_eval method_body(temp_method, safe_name), __FILE__, __LINE__
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/attribute_methods/read.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ module ClassMethods
protected

def define_method_attribute(name)
safe_name = name.unpack('h*').first
safe_name = name.unpack('h*'.freeze).first
temp_method = "__temp__#{safe_name}"

ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/attribute_methods/write.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ module ClassMethods
protected

def define_method_attribute=(name)
safe_name = name.unpack('h*').first
safe_name = name.unpack('h*'.freeze).first
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name

generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def initialize(type_metadata, oid: nil, fmod: nil)
end

def sql_type
super.gsub(/\[\]$/, "")
super.gsub(/\[\]$/, "".freeze)
end

def ==(other)
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/relation/delegation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def initialize_relation_delegate_cache # :nodoc:
delegate = Class.new(klass) {
include ClassSpecificRelation
}
const_set klass.name.gsub('::', '_'), delegate
const_set klass.name.gsub('::'.freeze, '_'.freeze), delegate
cache[klass] = delegate
end
end
Expand Down
6 changes: 3 additions & 3 deletions activerecord/lib/active_record/relation/predicate_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def self.references(attributes)
key
else
key = key.to_s
key.split('.').first if key.include?('.')
key.split('.'.freeze).first if key.include?('.'.freeze)
end
end.compact
end
Expand Down Expand Up @@ -123,10 +123,10 @@ def associated_predicate_builder(association_name)
end

def convert_dot_notation_to_hash(attributes)
dot_notation = attributes.keys.select { |s| s.include?(".") }
dot_notation = attributes.keys.select { |s| s.include?(".".freeze) }

dot_notation.each do |key|
table_name, column_name = key.split(".")
table_name, column_name = key.split(".".freeze)
value = attributes.delete(key)
attributes[table_name] ||= {}

Expand Down
2 changes: 1 addition & 1 deletion activesupport/lib/active_support/core_ext/load_error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def path
# Returns true if the given path name (except perhaps for the ".rb"
# extension) is the missing file which caused the exception to be raised.
def is_missing?(location)
location.sub(/\.rb$/, '') == path.sub(/\.rb$/, '')
location.sub(/\.rb$/, ''.freeze) == path.sub(/\.rb$/, ''.freeze)
end
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def delegate(*methods)
''
end

file, line = caller(1, 1).first.split(':', 2)
file, line = caller(1, 1).first.split(':'.freeze, 2)
line = line.to_i

to = to.to_s
Expand Down
6 changes: 3 additions & 3 deletions activesupport/lib/active_support/dependencies.rb
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def new_constants

# Normalize the list of new constants, and add them to the list we will return
new_constants.each do |suffix|
constants << ([namespace, suffix] - ["Object"]).join("::")
constants << ([namespace, suffix] - ["Object"]).join("::".freeze)
end
end
constants
Expand Down Expand Up @@ -431,7 +431,7 @@ def loadable_constants_for_path(path, bases = autoload_paths)

# Search for a file in autoload_paths matching the provided suffix.
def search_for_file(path_suffix)
path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb")
path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb".freeze)

autoload_paths.each do |root|
path = File.join(root, path_suffix)
Expand Down Expand Up @@ -516,7 +516,7 @@ def load_missing_constant(from_mod, const_name)

if file_path
expanded = File.expand_path(file_path)
expanded.sub!(/\.rb\z/, '')
expanded.sub!(/\.rb\z/, ''.freeze)

if loading.include?(expanded)
raise "Circular dependency detected while autoloading constant #{qualified_name}"
Expand Down
Loading