Add Style/RedundantFreeze to remove redudant .freeze

Since Rails 6.0 will support Ruby 2.4.1 or higher
`# frozen_string_literal: true` magic comment is enough to make string object frozen.
This magic comment is enabled by `Style/FrozenStringLiteralComment` cop.

* Exclude these files not to auto correct false positive `Regexp#freeze`
 - 'actionpack/lib/action_dispatch/journey/router/utils.rb'
 - 'activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb'

It has been fixed by https://github.com/rubocop-hq/rubocop/pull/6333
Once the newer version of RuboCop released and available at Code Climate these exclude entries should be removed.

* Replace `String#freeze` with `String#-@` manually if explicit frozen string objects are required

 - 'actionpack/test/controller/test_case_test.rb'
 - 'activemodel/test/cases/type/string_test.rb'
 - 'activesupport/lib/active_support/core_ext/string/strip.rb'
 - 'activesupport/test/core_ext/string_ext_test.rb'
 - 'railties/test/generators/actions_test.rb'
This commit is contained in:
Yasuo Honda 2018-02-28 04:33:37 +00:00
parent 445a74e1a9
commit aa3dcabd87
109 changed files with 274 additions and 268 deletions

@ -130,6 +130,12 @@ Style/FrozenStringLiteralComment:
- 'actionpack/test/**/*.ruby'
- 'activestorage/db/migrate/**/*.rb'
Style/RedundantFreeze:
Enabled: true
Exclude:
- 'actionpack/lib/action_dispatch/journey/router/utils.rb'
- 'activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb'
# Use `foo {}` not `foo{}`.
Layout/SpaceBeforeBlockBraces:
Enabled: true

@ -32,13 +32,13 @@ module ActionCable
INTERNAL = {
message_types: {
welcome: "welcome".freeze,
ping: "ping".freeze,
confirmation: "confirm_subscription".freeze,
rejection: "reject_subscription".freeze
welcome: "welcome",
ping: "ping",
confirmation: "confirm_subscription",
rejection: "reject_subscription"
},
default_mount_path: "/cable".freeze,
protocols: ["actioncable-v1-json".freeze, "actioncable-unsupported".freeze].freeze
default_mount_path: "/cable",
protocols: ["actioncable-v1-json", "actioncable-unsupported"].freeze
}
# Singleton instance of the server

@ -1008,7 +1008,7 @@ def instrument_payload(key)
end
def instrument_name
"action_mailer".freeze
"action_mailer"
end
ActiveSupport.run_load_hooks(:action_mailer, self)

@ -104,7 +104,7 @@ def clear_action_methods!
# ==== Returns
# * <tt>String</tt>
def controller_path
@controller_path ||= name.sub(/Controller$/, "".freeze).underscore unless anonymous?
@controller_path ||= name.sub(/Controller$/, "").underscore unless anonymous?
end
# Refresh the cached action_methods when a new action_method is added.

@ -181,7 +181,7 @@ def add_template_helper(mod)
end
def default_helper_module!
module_name = name.sub(/Controller$/, "".freeze)
module_name = name.sub(/Controller$/, "")
module_path = module_name.underscore
helper module_path
rescue LoadError => e

@ -40,7 +40,7 @@ def instrument_payload(key)
end
def instrument_name
"action_controller".freeze
"action_controller"
end
end
end

@ -27,7 +27,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(" | ".freeze)})" unless additions.empty?
message << " (#{additions.join(" | ")})" unless additions.empty?
message << "\n\n" if defined?(Rails.env) && Rails.env.development?
message

@ -11,8 +11,8 @@ module DataStreaming
include ActionController::Rendering
DEFAULT_SEND_FILE_TYPE = "application/octet-stream".freeze #:nodoc:
DEFAULT_SEND_FILE_DISPOSITION = "attachment".freeze #:nodoc:
DEFAULT_SEND_FILE_TYPE = "application/octet-stream" #:nodoc:
DEFAULT_SEND_FILE_DISPOSITION = "attachment" #:nodoc:
private
# Sends the file. This uses a server-appropriate method (such as X-Sendfile)

@ -127,7 +127,7 @@ def encode_credentials(user_name, password)
def authentication_request(controller, realm, message)
message ||= "HTTP Basic: Access denied.\n"
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.tr('"'.freeze, "".freeze)}")
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.tr('"', "")}")
controller.status = 401
controller.response_body = message
end
@ -511,7 +511,7 @@ def encode_credentials(token, options = {})
# Returns nothing.
def authentication_request(controller, realm, message = nil)
message ||= "HTTP Token: Access denied.\n"
controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.tr('"'.freeze, "".freeze)}")
controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.tr('"', "")}")
controller.__send__ :render, plain: message, status: :unauthorized
end
end

@ -117,7 +117,7 @@ def perform_write(json, options)
end
end
message = json.gsub("\n".freeze, "\ndata: ".freeze)
message = json.gsub("\n", "\ndata: ")
@stream.write "data: #{message}\n\n"
end
end

@ -44,7 +44,7 @@ def url_options
options[:original_script_name] = original_script_name
else
if same_origin
options[:script_name] = request.script_name.empty? ? "".freeze : request.script_name.dup
options[:script_name] = request.script_name.empty? ? "" : request.script_name.dup
else
options[:script_name] = script_name
end

@ -4,8 +4,8 @@ module ActionDispatch
module Http
module Cache
module Request
HTTP_IF_MODIFIED_SINCE = "HTTP_IF_MODIFIED_SINCE".freeze
HTTP_IF_NONE_MATCH = "HTTP_IF_NONE_MATCH".freeze
HTTP_IF_MODIFIED_SINCE = "HTTP_IF_MODIFIED_SINCE"
HTTP_IF_NONE_MATCH = "HTTP_IF_NONE_MATCH"
def if_modified_since
if since = get_header(HTTP_IF_MODIFIED_SINCE)
@ -124,8 +124,8 @@ def strong_etag?
private
DATE = "Date".freeze
LAST_MODIFIED = "Last-Modified".freeze
DATE = "Date"
LAST_MODIFIED = "Last-Modified"
SPECIAL_KEYS = Set.new(%w[extras no-cache max-age public private must-revalidate])
def generate_weak_etag(validators)
@ -166,11 +166,11 @@ def prepare_cache_control!
@cache_control = cache_control_headers
end
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
NO_CACHE = "no-cache".freeze
PUBLIC = "public".freeze
PRIVATE = "private".freeze
MUST_REVALIDATE = "must-revalidate".freeze
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate"
NO_CACHE = "no-cache"
PUBLIC = "public"
PRIVATE = "private"
MUST_REVALIDATE = "must-revalidate"
def handle_conditional_get!
# Normally default cache control setting is handled by ETag

@ -5,9 +5,9 @@
module ActionDispatch #:nodoc:
class ContentSecurityPolicy
class Middleware
CONTENT_TYPE = "Content-Type".freeze
POLICY = "Content-Security-Policy".freeze
POLICY_REPORT_ONLY = "Content-Security-Policy-Report-Only".freeze
CONTENT_TYPE = "Content-Type"
POLICY = "Content-Security-Policy"
POLICY_REPORT_ONLY = "Content-Security-Policy-Report-Only"
def initialize(app)
@app = app
@ -50,10 +50,10 @@ def policy_present?(headers)
end
module Request
POLICY = "action_dispatch.content_security_policy".freeze
POLICY_REPORT_ONLY = "action_dispatch.content_security_policy_report_only".freeze
NONCE_GENERATOR = "action_dispatch.content_security_policy_nonce_generator".freeze
NONCE = "action_dispatch.content_security_policy_nonce".freeze
POLICY = "action_dispatch.content_security_policy"
POLICY_REPORT_ONLY = "action_dispatch.content_security_policy_report_only"
NONCE_GENERATOR = "action_dispatch.content_security_policy_nonce_generator"
NONCE = "action_dispatch.content_security_policy_nonce"
def content_security_policy
get_header(POLICY)

@ -3,7 +3,7 @@
module ActionDispatch
module Http
module FilterRedirect
FILTERED = "[FILTERED]".freeze # :nodoc:
FILTERED = "[FILTERED]" # :nodoc:
def filtered_location # :nodoc:
if location_filter_match?

@ -74,7 +74,7 @@ class AcceptItem #:nodoc:
def initialize(index, name, q = nil)
@index = index
@name = name
q ||= 0.0 if @name == "*/*".freeze # Default wildcard match to end of list.
q ||= 0.0 if @name == "*/*" # Default wildcard match to end of list.
@q = ((q || 1.0).to_f * 100).to_i
end

@ -6,7 +6,7 @@
module ActionDispatch
module Http
class ParameterFilter
FILTERED = "[FILTERED]".freeze # :nodoc:
FILTERED = "[FILTERED]" # :nodoc:
def initialize(filters = [])
@filters = filters
@ -39,11 +39,11 @@ def self.compile(filters)
end
end
deep_regexps = regexps.extract! { |r| r.to_s.include?("\\.".freeze) }
deep_strings = strings.extract! { |s| s.include?("\\.".freeze) }
deep_regexps = regexps.extract! { |r| r.to_s.include?("\\.") }
deep_strings = strings.extract! { |s| s.include?("\\.") }
regexps << Regexp.new(strings.join("|".freeze), true) unless strings.empty?
deep_regexps << Regexp.new(deep_strings.join("|".freeze), true) unless deep_strings.empty?
regexps << Regexp.new(strings.join("|"), true) unless strings.empty?
deep_regexps << Regexp.new(deep_strings.join("|"), true) unless deep_strings.empty?
new regexps, deep_regexps, blocks
end

@ -136,11 +136,11 @@ def request_method
end
def routes # :nodoc:
get_header("action_dispatch.routes".freeze)
get_header("action_dispatch.routes")
end
def routes=(routes) # :nodoc:
set_header("action_dispatch.routes".freeze, routes)
set_header("action_dispatch.routes", routes)
end
def engine_script_name(_routes) # :nodoc:
@ -158,11 +158,11 @@ def request_method=(request_method) #:nodoc:
end
def controller_instance # :nodoc:
get_header("action_controller.instance".freeze)
get_header("action_controller.instance")
end
def controller_instance=(controller) # :nodoc:
set_header("action_controller.instance".freeze, controller)
set_header("action_controller.instance", controller)
end
def http_auth_salt
@ -173,7 +173,7 @@ def show_exceptions? # :nodoc:
# We're treating `nil` as "unset", and we want the default setting to be
# `true`. This logic should be extracted to `env_config` and calculated
# once.
!(get_header("action_dispatch.show_exceptions".freeze) == false)
!(get_header("action_dispatch.show_exceptions") == false)
end
# Returns a symbol form of the #request_method.
@ -280,10 +280,10 @@ def remote_ip
end
def remote_ip=(remote_ip)
set_header "action_dispatch.remote_ip".freeze, remote_ip
set_header "action_dispatch.remote_ip", remote_ip
end
ACTION_DISPATCH_REQUEST_ID = "action_dispatch.request_id".freeze # :nodoc:
ACTION_DISPATCH_REQUEST_ID = "action_dispatch.request_id" # :nodoc:
# Returns the unique request id, which is based on either the X-Request-Id header that can
# be generated by a firewall, load balancer, or web server or by the RequestId middleware
@ -407,18 +407,18 @@ def local?
def request_parameters=(params)
raise if params.nil?
set_header("action_dispatch.request.request_parameters".freeze, params)
set_header("action_dispatch.request.request_parameters", params)
end
def logger
get_header("action_dispatch.logger".freeze)
get_header("action_dispatch.logger")
end
def commit_flash
end
def ssl?
super || scheme == "wss".freeze
super || scheme == "wss"
end
private

@ -78,9 +78,9 @@ def each(&block)
x
end
CONTENT_TYPE = "Content-Type".freeze
SET_COOKIE = "Set-Cookie".freeze
LOCATION = "Location".freeze
CONTENT_TYPE = "Content-Type"
SET_COOKIE = "Set-Cookie"
LOCATION = "Location"
NO_CONTENT_CODES = [100, 101, 102, 204, 205, 304]
cattr_accessor :default_charset, default: "utf-8"

@ -67,7 +67,7 @@ def full_url_for(options)
end
def path_for(options)
path = options[:script_name].to_s.chomp("/".freeze)
path = options[:script_name].to_s.chomp("/")
path << options[:path] if options.key?(:path)
add_trailing_slash(path) if options[:trailing_slash]
@ -231,7 +231,7 @@ def raw_host_with_port
# req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080'
# req.host # => "example.com"
def host
raw_host_with_port.sub(/:\d+$/, "".freeze)
raw_host_with_port.sub(/:\d+$/, "")
end
# Returns a \host:\port string for this request, such as "example.com" or

@ -18,10 +18,10 @@ def self.normalize_path(path)
path ||= ""
encoding = path.encoding
path = +"/#{path}"
path.squeeze!("/".freeze)
path.sub!(%r{/+\Z}, "".freeze)
path.squeeze!("/")
path.sub!(%r{/+\Z}, "")
path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
path = +"/" if path == "".freeze
path = +"/" if path == ""
path.force_encoding(encoding)
path
end
@ -29,16 +29,16 @@ def self.normalize_path(path)
# URI path and fragment escaping
# https://tools.ietf.org/html/rfc3986
class UriEncoder # :nodoc:
ENCODE = "%%%02X".freeze
ENCODE = "%%%02X"
US_ASCII = Encoding::US_ASCII
UTF_8 = Encoding::UTF_8
EMPTY = (+"").force_encoding(US_ASCII).freeze
DEC2HEX = (0..255).to_a.map { |i| ENCODE % i }.map { |s| s.force_encoding(US_ASCII) }
ALPHA = "a-zA-Z".freeze
DIGIT = "0-9".freeze
UNRESERVED = "#{ALPHA}#{DIGIT}\\-\\._~".freeze
SUB_DELIMS = "!\\$&'\\(\\)\\*\\+,;=".freeze
ALPHA = "a-zA-Z"
DIGIT = "0-9"
UNRESERVED = "#{ALPHA}#{DIGIT}\\-\\._~"
SUB_DELIMS = "!\\$&'\\(\\)\\*\\+,;="
ESCAPED = /%[a-zA-Z0-9]{2}/.freeze

@ -40,7 +40,7 @@ def evaluate(hash)
@parameters.each do |index|
param = parts[index]
value = hash[param.name]
return "".freeze unless value
return "" unless value
parts[index] = param.escape value
end

@ -9,7 +9,7 @@
module ActionDispatch
class Request
def cookie_jar
fetch_header("action_dispatch.cookies".freeze) do
fetch_header("action_dispatch.cookies") do
self.cookie_jar = Cookies::CookieJar.build(self, cookies)
end
end
@ -22,11 +22,11 @@ def commit_cookie_jar!
}
def have_cookie_jar?
has_header? "action_dispatch.cookies".freeze
has_header? "action_dispatch.cookies"
end
def cookie_jar=(jar)
set_header "action_dispatch.cookies".freeze, jar
set_header "action_dispatch.cookies", jar
end
def key_generator
@ -172,21 +172,21 @@ def use_cookies_with_metadata
# * <tt>:httponly</tt> - Whether this cookie is accessible via scripting or
# only HTTP. Defaults to +false+.
class Cookies
HTTP_HEADER = "Set-Cookie".freeze
GENERATOR_KEY = "action_dispatch.key_generator".freeze
SIGNED_COOKIE_SALT = "action_dispatch.signed_cookie_salt".freeze
ENCRYPTED_COOKIE_SALT = "action_dispatch.encrypted_cookie_salt".freeze
ENCRYPTED_SIGNED_COOKIE_SALT = "action_dispatch.encrypted_signed_cookie_salt".freeze
AUTHENTICATED_ENCRYPTED_COOKIE_SALT = "action_dispatch.authenticated_encrypted_cookie_salt".freeze
USE_AUTHENTICATED_COOKIE_ENCRYPTION = "action_dispatch.use_authenticated_cookie_encryption".freeze
ENCRYPTED_COOKIE_CIPHER = "action_dispatch.encrypted_cookie_cipher".freeze
SIGNED_COOKIE_DIGEST = "action_dispatch.signed_cookie_digest".freeze
SECRET_TOKEN = "action_dispatch.secret_token".freeze
SECRET_KEY_BASE = "action_dispatch.secret_key_base".freeze
COOKIES_SERIALIZER = "action_dispatch.cookies_serializer".freeze
COOKIES_DIGEST = "action_dispatch.cookies_digest".freeze
COOKIES_ROTATIONS = "action_dispatch.cookies_rotations".freeze
USE_COOKIES_WITH_METADATA = "action_dispatch.use_cookies_with_metadata".freeze
HTTP_HEADER = "Set-Cookie"
GENERATOR_KEY = "action_dispatch.key_generator"
SIGNED_COOKIE_SALT = "action_dispatch.signed_cookie_salt"
ENCRYPTED_COOKIE_SALT = "action_dispatch.encrypted_cookie_salt"
ENCRYPTED_SIGNED_COOKIE_SALT = "action_dispatch.encrypted_signed_cookie_salt"
AUTHENTICATED_ENCRYPTED_COOKIE_SALT = "action_dispatch.authenticated_encrypted_cookie_salt"
USE_AUTHENTICATED_COOKIE_ENCRYPTION = "action_dispatch.use_authenticated_cookie_encryption"
ENCRYPTED_COOKIE_CIPHER = "action_dispatch.encrypted_cookie_cipher"
SIGNED_COOKIE_DIGEST = "action_dispatch.signed_cookie_digest"
SECRET_TOKEN = "action_dispatch.secret_token"
SECRET_KEY_BASE = "action_dispatch.secret_key_base"
COOKIES_SERIALIZER = "action_dispatch.cookies_serializer"
COOKIES_DIGEST = "action_dispatch.cookies_digest"
COOKIES_ROTATIONS = "action_dispatch.cookies_rotations"
USE_COOKIES_WITH_METADATA = "action_dispatch.use_cookies_with_metadata"
# Cookies can typically store 4096 bytes.
MAX_COOKIE_SIZE = 4096
@ -535,7 +535,7 @@ def self.dump(value)
end
module SerializedCookieJars # :nodoc:
MARSHAL_SIGNATURE = "\x04\x08".freeze
MARSHAL_SIGNATURE = "\x04\x08"
SERIALIZER = ActiveSupport::MessageEncryptor::NullSerializer
protected

@ -32,7 +32,7 @@ def call(env)
req = ActionDispatch::Request.new env
if req.get?
path = req.path_info.chomp("/".freeze)
path = req.path_info.chomp("/")
if path == @path
return render_details(req)
end

@ -38,7 +38,7 @@ module ActionDispatch
#
# See docs on the FlashHash class for more details about the flash.
class Flash
KEY = "action_dispatch.request.flash_hash".freeze
KEY = "action_dispatch.request.flash_hash"
module RequestMethods
# Access the contents of the flash. Use <tt>flash["notice"]</tt> to

@ -15,7 +15,7 @@ module ActionDispatch
# The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
# from multiple pieces of the stack.
class RequestId
X_REQUEST_ID = "X-Request-Id".freeze #:nodoc:
X_REQUEST_ID = "X-Request-Id" #:nodoc:
def initialize(app)
@app = app
@ -30,7 +30,7 @@ def call(env)
private
def make_request_id(request_id)
if request_id.presence
request_id.gsub(/[^\w\-@]/, "".freeze).first(255)
request_id.gsub(/[^\w\-@]/, "").first(255)
else
internal_request_id
end

@ -83,7 +83,7 @@ def call(env)
private
def set_hsts_header!(headers)
headers["Strict-Transport-Security".freeze] ||= @hsts_header
headers["Strict-Transport-Security"] ||= @hsts_header
end
def normalize_hsts_options(options)
@ -109,16 +109,16 @@ def build_hsts_header(hsts)
end
def flag_cookies_as_secure!(headers)
if cookies = headers["Set-Cookie".freeze]
cookies = cookies.split("\n".freeze)
if cookies = headers["Set-Cookie"]
cookies = cookies.split("\n")
headers["Set-Cookie".freeze] = cookies.map { |cookie|
headers["Set-Cookie"] = cookies.map { |cookie|
if !/;\s*secure\s*(;|$)/i.match?(cookie)
"#{cookie}; secure"
else
cookie
end
}.join("\n".freeze)
}.join("\n")
end
end

@ -79,7 +79,7 @@ def ext
end
def content_type(path)
::Rack::Mime.mime_type(::File.extname(path), "text/plain".freeze)
::Rack::Mime.mime_type(::File.extname(path), "text/plain")
end
def gzip_encoding_accepted?(request)
@ -116,7 +116,7 @@ def call(env)
req = Rack::Request.new env
if req.get? || req.head?
path = req.path_info.chomp("/".freeze)
path = req.path_info.chomp("/")
if match = @file_handler.match?(path)
req.path_info = match
return @file_handler.serve(req)

@ -679,7 +679,7 @@ def define_generate_prefix(app, name)
script_namer = ->(options) do
prefix_options = options.slice(*_route.segment_keys)
prefix_options[:relative_url_root] = "".freeze
prefix_options[:relative_url_root] = ""
if options[:_recall]
prefix_options.reverse_merge!(options[:_recall].slice(*_route.segment_keys))

@ -181,8 +181,8 @@ def self.get(action, type)
CACHE[type].fetch(action) { build action, type }
end
def self.url; CACHE["url".freeze][nil]; end
def self.path; CACHE["path".freeze][nil]; end
def self.url; CACHE["url"][nil]; end
def self.path; CACHE["path"][nil]; end
def self.build(action, type)
prefix = action ? "#{action}_" : ""

@ -377,7 +377,7 @@ def initialize(config = DEFAULT_CONFIG)
@prepend = []
@disable_clear_and_finalize = false
@finalized = false
@env_key = "ROUTES_#{object_id}_SCRIPT_NAME".freeze
@env_key = "ROUTES_#{object_id}_SCRIPT_NAME"
@url_helpers = nil
@deferred_classes = []
@ -767,7 +767,7 @@ def use_relative_controller!
# Remove leading slashes from controllers
def normalize_controller!
if controller
if controller.start_with?("/".freeze)
if controller.start_with?("/")
@options[:controller] = controller[1..-1]
else
@options[:controller] = controller

@ -25,8 +25,8 @@ def setup
safe, unsafe = %w(: @ & = + $ , ;), %w(^ ? # [ ])
hex = unsafe.map { |char| "%" + char.unpack1("H2").upcase }
@segment = "#{safe.join}#{unsafe.join}".freeze
@escaped = "#{safe.join}#{hex.join}".freeze
@segment = "#{safe.join}#{unsafe.join}"
@escaped = "#{safe.join}#{hex.join}"
end
def test_route_generation_escapes_unsafe_path_characters

@ -542,7 +542,7 @@ def test_params_passing_path_parameter_is_string_when_not_html_request
def test_params_passing_with_frozen_values
assert_nothing_raised do
get :test_params, params: {
frozen: "icy".freeze, frozens: ["icy".freeze].freeze, deepfreeze: { frozen: "icy".freeze }.freeze
frozen: -"icy", frozens: [-"icy"].freeze, deepfreeze: { frozen: -"icy" }.freeze
}
end
parsed_params = ::JSON.parse(@response.body)

@ -98,7 +98,7 @@ def javascript_include_tag(*sources)
if tag_options["nonce"] == true
tag_options["nonce"] = content_security_policy_nonce
end
content_tag("script".freeze, "", tag_options)
content_tag("script", "", tag_options)
}.join("\n").html_safe
request.send_early_hints("Link" => early_hints_links.join("\n")) if respond_to?(:request) && request
@ -375,7 +375,7 @@ def image_tag(source, options = {})
def image_alt(src)
ActiveSupport::Deprecation.warn("image_alt is deprecated and will be removed from Rails 6.0. You must explicitly set alt text on images.")
File.basename(src, ".*".freeze).sub(/-[[:xdigit:]]{32,64}\z/, "".freeze).tr("-_".freeze, " ".freeze).capitalize
File.basename(src, ".*").sub(/-[[:xdigit:]]{32,64}\z/, "").tr("-_", " ").capitalize
end
# Returns an HTML video tag for the +sources+. If +sources+ is a string,

@ -188,7 +188,7 @@ def asset_path(source, options = {})
return "" if source.blank?
return source if URI_REGEXP.match?(source)
tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, "".freeze)
tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, "")
if extname = compute_asset_extname(source, options)
source = "#{source}#{extname}"

@ -684,7 +684,7 @@ def time_tag(date_or_time, *args, &block)
format = options.delete(:format) || :long
content = args.first || I18n.l(date_or_time, format: format)
content_tag("time".freeze, content, options.reverse_merge(datetime: date_or_time.iso8601), &block)
content_tag("time", content, options.reverse_merge(datetime: date_or_time.iso8601), &block)
end
private
@ -703,7 +703,7 @@ def normalize_distance_of_time_argument_to_time(value)
class DateTimeSelector #:nodoc:
include ActionView::Helpers::TagHelper
DEFAULT_PREFIX = "date".freeze
DEFAULT_PREFIX = "date"
POSITION = {
year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6
}.freeze
@ -824,7 +824,7 @@ def select_month
1.upto(12) do |month_number|
options = { value: month_number }
options[:selected] = "selected" if month == month_number
month_options << content_tag("option".freeze, month_name(month_number), options) + "\n"
month_options << content_tag("option", month_name(month_number), options) + "\n"
end
build_select(:month, month_options.join)
end
@ -1006,7 +1006,7 @@ def build_options(selected, options = {})
tag_options[:selected] = "selected" if selected == i
text = options[:use_two_digit_numbers] ? sprintf("%02d", i) : value
text = options[:ampm] ? AMPM_TRANSLATION[i] : text
select_options << content_tag("option".freeze, text, tag_options)
select_options << content_tag("option", text, tag_options)
end
(select_options.join("\n") + "\n").html_safe
@ -1034,7 +1034,7 @@ def build_year_options(selected, options = {})
tag_options = { value: value }
tag_options[:selected] = "selected" if selected == value
text = year_name(value)
select_options << content_tag("option".freeze, text, tag_options)
select_options << content_tag("option", text, tag_options)
end
(select_options.join("\n") + "\n").html_safe
@ -1054,11 +1054,11 @@ def build_select(type, select_options_as_html)
select_options[:class] = css_class_attribute(type, select_options[:class], @options[:with_css_classes]) if @options[:with_css_classes]
select_html = +"\n"
select_html << content_tag("option".freeze, "", value: "") + "\n" if @options[:include_blank]
select_html << content_tag("option", "", value: "") + "\n" if @options[:include_blank]
select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt]
select_html << select_options_as_html
(content_tag("select".freeze, select_html.html_safe, select_options) + "\n").html_safe
(content_tag("select", select_html.html_safe, select_options) + "\n").html_safe
end
# Builds the css class value for the select element
@ -1091,7 +1091,7 @@ def prompt_option_tag(type, options)
I18n.translate(:"datetime.prompts.#{type}", locale: @options[:locale])
end
prompt ? content_tag("option".freeze, prompt, value: "") : ""
prompt ? content_tag("option", prompt, value: "") : ""
end
# Builds hidden input tag for date part and value.

@ -463,7 +463,7 @@ def option_groups_from_collection_for_select(collection, group_method, group_lab
option_tags = options_from_collection_for_select(
value_for_collection(group, group_method), option_key_method, option_value_method, selected_key)
content_tag("optgroup".freeze, option_tags, label: value_for_collection(group, group_label_method))
content_tag("optgroup", option_tags, label: value_for_collection(group, group_label_method))
end.join.html_safe
end
@ -535,7 +535,7 @@ def grouped_options_for_select(grouped_options, selected_key = nil, options = {}
body = "".html_safe
if prompt
body.safe_concat content_tag("option".freeze, prompt_text(prompt), value: "")
body.safe_concat content_tag("option", prompt_text(prompt), value: "")
end
grouped_options.each do |container|
@ -548,7 +548,7 @@ def grouped_options_for_select(grouped_options, selected_key = nil, options = {}
end
html_attributes = { label: label }.merge!(html_attributes)
body.safe_concat content_tag("optgroup".freeze, options_for_select(container, selected_key), html_attributes)
body.safe_concat content_tag("optgroup", options_for_select(container, selected_key), html_attributes)
end
body
@ -584,7 +584,7 @@ def time_zone_options_for_select(selected = nil, priority_zones = nil, model = :
end
zone_options.safe_concat options_for_select(convert_zones[priority_zones], selected)
zone_options.safe_concat content_tag("option".freeze, "-------------", value: "", disabled: true)
zone_options.safe_concat content_tag("option", "-------------", value: "", disabled: true)
zone_options.safe_concat "\n"
zones = zones - priority_zones

@ -146,15 +146,15 @@ def select_tag(name, option_tags = nil, options = {})
end
if include_blank
option_tags = content_tag("option".freeze, include_blank, options_for_blank_options_tag).safe_concat(option_tags)
option_tags = content_tag("option", include_blank, options_for_blank_options_tag).safe_concat(option_tags)
end
end
if prompt = options.delete(:prompt)
option_tags = content_tag("option".freeze, prompt, value: "").safe_concat(option_tags)
option_tags = content_tag("option", prompt, value: "").safe_concat(option_tags)
end
content_tag "select".freeze, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
content_tag "select", option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
end
# Creates a standard text field; use these text fields to input smaller chunks of text like a username
@ -577,7 +577,7 @@ def image_submit_tag(source, options = {})
# # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset>
def field_set_tag(legend = nil, options = nil, &block)
output = tag(:fieldset, options, true)
output.safe_concat(content_tag("legend".freeze, legend)) unless legend.blank?
output.safe_concat(content_tag("legend", legend)) unless legend.blank?
output.concat(capture(&block)) if block_given?
output.safe_concat("</fieldset>")
end

@ -84,7 +84,7 @@ def javascript_tag(content_or_options_with_block = nil, html_options = {}, &bloc
html_options[:nonce] = content_security_policy_nonce
end
content_tag("script".freeze, javascript_cdata_section(content), html_options)
content_tag("script", javascript_cdata_section(content), html_options)
end
def javascript_cdata_section(content) #:nodoc:

@ -86,11 +86,11 @@ def boolean_tag_option(key)
def tag_option(key, value, escape)
if value.is_a?(Array)
value = escape ? safe_join(value, " ".freeze) : value.join(" ".freeze)
value = escape ? safe_join(value, " ") : value.join(" ")
else
value = escape ? ERB::Util.unwrapped_html_escape(value) : value.to_s.dup
end
value.gsub!('"'.freeze, "&quot;".freeze)
value.gsub!('"', "&quot;")
%(#{key}="#{value}")
end

@ -200,9 +200,9 @@ def link_to(name = nil, options = nil, html_options = nil, &block)
html_options = convert_options_to_data_attributes(options, html_options)
url = url_for(options)
html_options["href".freeze] ||= url
html_options["href"] ||= url
content_tag("a".freeze, name || url, html_options, &block)
content_tag("a", name || url, html_options, &block)
end
# Generates a form containing a single button that submits to the URL created
@ -308,7 +308,7 @@ def button_to(name = nil, options = nil, html_options = nil, &block)
params = html_options.delete("params")
method = html_options.delete("method").to_s
method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : "".freeze.html_safe
method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : "".html_safe
form_method = method == "get" ? "get" : "post"
form_options = html_options.delete("form") || {}
@ -321,7 +321,7 @@ def button_to(name = nil, options = nil, html_options = nil, &block)
request_method = method.empty? ? "post" : method
token_tag(nil, form_options: { action: url, method: request_method })
else
"".freeze
""
end
html_options = convert_options_to_data_attributes(options, html_options)
@ -487,12 +487,12 @@ def mail_to(email_address, name = nil, html_options = {}, &block)
option = html_options.delete(item).presence || next
"#{item.dasherize}=#{ERB::Util.url_encode(option)}"
}.compact
extras = extras.empty? ? "".freeze : "?" + extras.join("&")
extras = extras.empty? ? "" : "?" + extras.join("&")
encoded_email_address = ERB::Util.url_encode(email_address).gsub("%40", "@")
html_options["href"] = "mailto:#{encoded_email_address}#{extras}"
content_tag("a".freeze, name || email_address, html_options, &block)
content_tag("a", name || email_address, html_options, &block)
end
# True if the current request URI was generated by the given +options+.
@ -575,21 +575,21 @@ def current_page?(options, check_parameters: false)
def convert_options_to_data_attributes(options, html_options)
if html_options
html_options = html_options.stringify_keys
html_options["data-remote"] = "true".freeze if link_to_remote_options?(options) || link_to_remote_options?(html_options)
html_options["data-remote"] = "true" if link_to_remote_options?(options) || link_to_remote_options?(html_options)
method = html_options.delete("method".freeze)
method = html_options.delete("method")
add_method_to_attributes!(html_options, method) if method
html_options
else
link_to_remote_options?(options) ? { "data-remote" => "true".freeze } : {}
link_to_remote_options?(options) ? { "data-remote" => "true" } : {}
end
end
def link_to_remote_options?(options)
if options.is_a?(Hash)
options.delete("remote".freeze) || options.delete(:remote)
options.delete("remote") || options.delete(:remote)
end
end
@ -622,7 +622,7 @@ def token_tag(token = nil, form_options: {})
token ||= form_authenticity_token(form_options: form_options)
tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token)
else
"".freeze
""
end
end

@ -202,13 +202,13 @@ def detail_args_for_any
# name instead of the prefix.
def normalize_name(name, prefixes)
prefixes = prefixes.presence
parts = name.to_s.split("/".freeze)
parts = name.to_s.split("/")
parts.shift if parts.first.empty?
name = parts.pop
return name, prefixes || [""] if parts.empty?
parts = parts.join("/".freeze)
parts = parts.join("/")
prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]
return name, prefixes
@ -245,7 +245,7 @@ def initialize_details(target, details)
# add :html as fallback to :js.
def formats=(values)
if values
values.concat(default_formats) if values.delete "*/*".freeze
values.concat(default_formats) if values.delete "*/*"
if values == [:js]
values << :html
@html_fallback_for_js = true

@ -59,8 +59,8 @@ module RecordIdentifier
include ModelNaming
JOIN = "_".freeze
NEW = "new".freeze
JOIN = "_"
NEW = "new"
# The DOM class convention is to use the singular form of an object or class.
#

@ -523,7 +523,7 @@ def retrieve_template_keys
def retrieve_variable(path, as)
variable = as || begin
base = path[-1] == "/".freeze ? "".freeze : File.basename(path)
base = path[-1] == "/" ? "" : File.basename(path)
raise_invalid_identifier(path) unless base =~ /\A_?(.*?)(?:\.\w+)*\z/
$1.to_sym
end

@ -188,7 +188,7 @@ def refresh(view)
end
def inspect
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", "".freeze) : identifier
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", "") : identifier
end
# This method is responsible for properly setting the encoding of the
@ -341,13 +341,13 @@ def locals_code
def method_name
@method_name ||= begin
m = +"_#{identifier_method_name}__#{@identifier.hash}_#{__id__}"
m.tr!("-".freeze, "_".freeze)
m.tr!("-", "_")
m
end
end
def identifier_method_name
inspect.tr("^a-z_".freeze, "_".freeze)
inspect.tr("^a-z_", "_")
end
def instrument(action, &block) # :doc:
@ -355,7 +355,7 @@ def instrument(action, &block) # :doc:
end
def instrument_render_template(&block)
ActiveSupport::Notifications.instrument("!render_template.action_view".freeze, instrument_payload, &block)
ActiveSupport::Notifications.instrument("!render_template.action_view", instrument_payload, &block)
end
def instrument_payload

@ -282,7 +282,7 @@ def build_query(path, details)
end
def escape_entry(entry)
entry.gsub(/[*?{}\[\]]/, '\\\\\\&'.freeze)
entry.gsub(/[*?{}\[\]]/, '\\\\\\&')
end
# Returns the file mtime from the filesystem.
@ -294,7 +294,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)
pieces = File.basename(path).split(".".freeze)
pieces = File.basename(path).split(".")
pieces.shift
extension = pieces.pop

@ -34,10 +34,10 @@ def test_simple_format
assert_equal "<p>A paragraph</p>\n\n<p>and another one!</p>", simple_format("A paragraph\n\nand another one!")
assert_equal "<p>A paragraph\n<br /> With a newline</p>", simple_format("A paragraph\n With a newline")
text = "A\nB\nC\nD".freeze
text = "A\nB\nC\nD"
assert_equal "<p>A\n<br />B\n<br />C\n<br />D</p>", simple_format(text)
text = "A\r\n \nB\n\n\r\n\t\nC\nD".freeze
text = "A\r\n \nB\n\n\r\n\t\nC\nD"
assert_equal "<p>A\n<br /> \n<br />B</p>\n\n<p>\t\n<br />C\n<br />D</p>", simple_format(text)
assert_equal '<p class="test">This is a classy test</p>', simple_format("This is a classy test", class: "test")

@ -47,11 +47,11 @@ def deserialize(arguments)
private
# :nodoc:
GLOBALID_KEY = "_aj_globalid".freeze
GLOBALID_KEY = "_aj_globalid"
# :nodoc:
SYMBOL_KEYS_KEY = "_aj_symbol_keys".freeze
SYMBOL_KEYS_KEY = "_aj_symbol_keys"
# :nodoc:
WITH_INDIFFERENT_ACCESS_KEY = "_aj_hash_with_indifferent_access".freeze
WITH_INDIFFERENT_ACCESS_KEY = "_aj_hash_with_indifferent_access"
# :nodoc:
OBJECT_SERIALIZER_KEY = "_aj_serialized"

@ -121,7 +121,7 @@ module QueueAdapters
autoload :SuckerPunchAdapter
autoload :TestAdapter
ADAPTER = "Adapter".freeze
ADAPTER = "Adapter"
private_constant :ADAPTER
class << self

@ -369,7 +369,7 @@ def define_proxy_call(include_private, mod, name, send, *extra)
"define_method(:'#{name}') do |*args|"
end
extra = (extra.map!(&:inspect) << "*args").join(", ".freeze)
extra = (extra.map!(&:inspect) << "*args").join(", ")
target = if CALL_COMPILABLE_REGEXP.match?(send)
"#{"self." unless include_private}#{send}(#{extra})"

@ -29,7 +29,7 @@ def attribute(name, type = Type::Value.new, **options)
private
def define_method_attribute=(name)
safe_name = name.unpack1("h*".freeze)
safe_name = name.unpack1("h*")
ActiveModel::AttributeMethods::AttrNames.set_name_cache safe_name, name
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1

@ -103,7 +103,7 @@ def _to_partial_path #:nodoc:
@_to_partial_path ||= begin
element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(name))
collection = ActiveSupport::Inflector.tableize(name)
"#{collection}/#{element}".freeze
"#{collection}/#{element}"
end
end
end

@ -209,7 +209,7 @@ def human(options = {})
private
def _singularize(string)
ActiveSupport::Inflector.underscore(string).tr("/".freeze, "_".freeze)
ActiveSupport::Inflector.underscore(string).tr("/", "_")
end
end

@ -16,8 +16,8 @@ def changed_in_place?(raw_old_value, new_value)
def cast_value(value)
case value
when ::String then ::String.new(value)
when true then "t".freeze
when false then "f".freeze
when true then "t"
when false then "f"
else value.to_s
end
end

@ -116,7 +116,7 @@ def validates(*attributes)
key = "#{key.to_s.camelize}Validator"
begin
validator = key.include?("::".freeze) ? key.constantize : const_get(key)
validator = key.include?("::") ? key.constantize : const_get(key)
rescue NameError
raise ArgumentError, "Unknown validator: '#{key}'"
end

@ -19,7 +19,7 @@ class StringTest < ActiveModel::TestCase
assert_equal false, type.cast(s).frozen?
assert_equal false, s.frozen?
f = "foo".freeze
f = -"foo"
assert_equal false, type.cast(f).frozen?
assert_equal true, f.frozen?
end

@ -63,7 +63,7 @@ def self.suppress_composite_primary_key(pk)
def middle_reflection(join_model)
middle_name = [lhs_model.name.downcase.pluralize,
association_name].join("_".freeze).gsub("::".freeze, "_".freeze).to_sym
association_name].join("_").gsub("::", "_").to_sym
middle_options = middle_options join_model
HasMany.create_reflection(lhs_model,

@ -272,9 +272,9 @@ def respond_to?(name, include_private = false)
case name
when :to_partial_path
name = "to_partial_path".freeze
name = "to_partial_path"
when :to_model
name = "to_model".freeze
name = "to_model"
else
name = name.to_s
end

@ -27,7 +27,7 @@ module ClassMethods # :nodoc:
# Making it frozen means that it doesn't get duped when used to
# key the @attributes in read_attribute.
def define_method_attribute(name)
safe_name = name.unpack1("h*".freeze)
safe_name = name.unpack1("h*")
temp_method = "__temp__#{safe_name}"
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
@ -59,7 +59,7 @@ def read_attribute(attr_name, &block)
end
primary_key = self.class.primary_key
name = primary_key if name == "id".freeze && primary_key
name = primary_key if name == "id" && primary_key
sync_with_transaction_state if name == primary_key
_read_attribute(name, &block)
end

@ -13,7 +13,7 @@ module ClassMethods # :nodoc:
private
def define_method_attribute=(name)
safe_name = name.unpack1("h*".freeze)
safe_name = name.unpack1("h*")
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
sync_with_transaction_state = "sync_with_transaction_state" if name == primary_key
@ -40,7 +40,7 @@ def write_attribute(attr_name, value)
end
primary_key = self.class.primary_key
name = primary_key if name == "id".freeze && primary_key
name = primary_key if name == "id" && primary_key
sync_with_transaction_state if name == primary_key
_write_attribute(name, value)
end

@ -60,7 +60,7 @@ def lookup_cast_type_from_column(column) # :nodoc:
# Quotes a string, escaping any ' (single quote) and \ (backslash)
# characters.
def quote_string(s)
s.gsub('\\'.freeze, '\&\&'.freeze).gsub("'".freeze, "''".freeze) # ' (for ruby-mode)
s.gsub('\\', '\&\&').gsub("'", "''") # ' (for ruby-mode)
end
# Quotes the column name. Defaults to no quoting.
@ -95,7 +95,7 @@ def quote_default_expression(value, column) # :nodoc:
end
def quoted_true
"TRUE".freeze
"TRUE"
end
def unquoted_true
@ -103,7 +103,7 @@ def unquoted_true
end
def quoted_false
"FALSE".freeze
"FALSE"
end
def unquoted_false

@ -65,7 +65,7 @@ module ConnectionAdapters # :nodoc:
# Most of the methods in the adapter are useful during migrations. Most
# notably, the instance methods provided by SchemaStatements are very useful.
class AbstractAdapter
ADAPTER_NAME = "Abstract".freeze
ADAPTER_NAME = "Abstract"
include ActiveSupport::Callbacks
define_callbacks :checkout, :checkin

@ -5,7 +5,7 @@ module ConnectionAdapters
module MySQL
module Quoting # :nodoc:
def quote_column_name(name)
@quoted_column_names[name] ||= "`#{super.gsub('`', '``')}`".freeze
@quoted_column_names[name] ||= "`#{super.gsub('`', '``')}`"
end
def quote_table_name(name)

@ -14,7 +14,7 @@ def mysql2_connection(config)
config[:flags] ||= 0
if config[:flags].kind_of? Array
config[:flags].push "FOUND_ROWS".freeze
config[:flags].push "FOUND_ROWS"
else
config[:flags] |= Mysql2::Client::FOUND_ROWS
end
@ -32,7 +32,7 @@ def mysql2_connection(config)
module ConnectionAdapters
class Mysql2Adapter < AbstractMysqlAdapter
ADAPTER_NAME = "Mysql2".freeze
ADAPTER_NAME = "Mysql2"
include MySQL::DatabaseStatements

@ -19,10 +19,10 @@ def initialize(store)
def run(records)
nodes = records.reject { |row| @store.key? row["oid"].to_i }
mapped = nodes.extract! { |row| @store.key? row["typname"] }
ranges = nodes.extract! { |row| row["typtype"] == "r".freeze }
enums = nodes.extract! { |row| row["typtype"] == "e".freeze }
domains = nodes.extract! { |row| row["typtype"] == "d".freeze }
arrays = nodes.extract! { |row| row["typinput"] == "array_in".freeze }
ranges = nodes.extract! { |row| row["typtype"] == "r" }
enums = nodes.extract! { |row| row["typtype"] == "e" }
domains = nodes.extract! { |row| row["typtype"] == "d" }
arrays = nodes.extract! { |row| row["typinput"] == "array_in" }
composites = nodes.extract! { |row| row["typelem"].to_i != 0 }
mapped.each { |row| register_mapped_type(row) }

@ -17,7 +17,7 @@ def initialize(type_metadata, oid: nil, fmod: nil)
end
def sql_type
super.gsub(/\[\]$/, "".freeze)
super.gsub(/\[\]$/, "")
end
def ==(other)

@ -78,7 +78,7 @@ module ConnectionAdapters
# In addition, default connection parameters of libpq can be set per environment variables.
# See https://www.postgresql.org/docs/current/static/libpq-envars.html .
class PostgreSQLAdapter < AbstractAdapter
ADAPTER_NAME = "PostgreSQL".freeze
ADAPTER_NAME = "PostgreSQL"
NATIVE_DATABASE_TYPES = {
primary_key: "bigserial primary key",
@ -448,7 +448,7 @@ def translate_exception(exception, message)
end
end
def get_oid_type(oid, fmod, column_name, sql_type = "".freeze)
def get_oid_type(oid, fmod, column_name, sql_type = "")
if !type_map.key?(oid)
load_additional_types([oid])
end
@ -537,13 +537,13 @@ def extract_value_from_default(default)
# Quoted types
when /\A[\(B]?'(.*)'.*::"?([\w. ]+)"?(?:\[\])?\z/m
# The default 'now'::date is CURRENT_DATE
if $1 == "now".freeze && $2 == "date".freeze
if $1 == "now" && $2 == "date"
nil
else
$1.gsub("''".freeze, "'".freeze)
$1.gsub("''", "'")
end
# Boolean types
when "true".freeze, "false".freeze
when "true", "false"
default
# Numeric types
when /\A\(?(-?\d+(\.\d*)?)\)?(::bigint)?\z/
@ -655,7 +655,7 @@ def exec_cache(sql, name, binds)
#
# Check here for more details:
# https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
CACHED_PLAN_HEURISTIC = "cached plan must not change result type".freeze
CACHED_PLAN_HEURISTIC = "cached plan must not change result type"
def is_cached_plan_failure?(e)
pgerror = e.cause
code = pgerror.result.result_error_field(PG::PG_DIAG_SQLSTATE)

@ -13,7 +13,7 @@ def quote_table_name_for_assignment(table, attr)
end
def quote_column_name(name)
@quoted_column_names[name] ||= %Q("#{super.gsub('"', '""')}").freeze
@quoted_column_names[name] ||= %Q("#{super.gsub('"', '""')}")
end
def quoted_time(value)
@ -26,19 +26,19 @@ def quoted_binary(value)
end
def quoted_true
ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer ? "1".freeze : "'t'".freeze
ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer ? "1" : "'t'"
end
def unquoted_true
ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer ? 1 : "t".freeze
ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer ? 1 : "t"
end
def quoted_false
ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer ? "0".freeze : "'f'".freeze
ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer ? "0" : "'f'"
end
def unquoted_false
ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer ? 0 : "f".freeze
ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer ? 0 : "f"
end
private

@ -56,7 +56,7 @@ module ConnectionAdapters #:nodoc:
#
# * <tt>:database</tt> - Path to the database file.
class SQLite3Adapter < AbstractAdapter
ADAPTER_NAME = "SQLite".freeze
ADAPTER_NAME = "SQLite"
include SQLite3::Quoting
include SQLite3::SchemaStatements

@ -180,7 +180,7 @@ def inherited(subclass)
# Returns the class type of the record using the current module as a prefix. So descendants of
# MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
def compute_type(type_name)
if type_name.start_with?("::".freeze)
if type_name.start_with?("::")
# If the type is prefixed with a scope operator then we assume that
# the type_name is an absolute reference.
ActiveSupport::Dependencies.constantize(type_name)

@ -140,8 +140,8 @@ def initialize(message = nil)
end
class ConcurrentMigrationError < MigrationError #:nodoc:
DEFAULT_MESSAGE = "Cannot run migrations because another migration process is currently running.".freeze
RELEASE_LOCK_FAILED_MESSAGE = "Failed to release advisory lock".freeze
DEFAULT_MESSAGE = "Cannot run migrations because another migration process is currently running."
RELEASE_LOCK_FAILED_MESSAGE = "Failed to release advisory lock"
def initialize(message = DEFAULT_MESSAGE)
super

@ -17,7 +17,7 @@ def initialize_relation_delegate_cache
delegate = Class.new(klass) {
include ClassSpecificRelation
}
mangled_name = klass.name.gsub("::".freeze, "_".freeze)
mangled_name = klass.name.gsub("::", "_")
const_set mangled_name, delegate
private_constant mangled_name

@ -27,7 +27,7 @@ def self.references(attributes)
key
else
key = key.to_s
key.split(".".freeze).first if key.include?(".".freeze)
key.split(".").first if key.include?(".")
end
end.compact
end
@ -115,11 +115,11 @@ def associated_predicate_builder(association_name)
def convert_dot_notation_to_hash(attributes)
dot_notation = attributes.select do |k, v|
k.include?(".".freeze) && !v.is_a?(Hash)
k.include?(".") && !v.is_a?(Hash)
end
dot_notation.each_key do |key|
table_name, column_name = key.split(".".freeze)
table_name, column_name = key.split(".")
value = attributes.delete(key)
attributes[table_name] ||= {}

@ -939,7 +939,7 @@ def build_arel(aliases)
arel.having(having_clause.ast) unless having_clause.empty?
if limit_value
limit_attribute = ActiveModel::Attribute.with_cast_value(
"LIMIT".freeze,
"LIMIT",
connection.sanitize_limit(limit_value),
Type.default_value,
)
@ -947,7 +947,7 @@ def build_arel(aliases)
end
if offset_value
offset_attribute = ActiveModel::Attribute.with_cast_value(
"OFFSET".freeze,
"OFFSET",
offset_value.to_i,
Type.default_value,
)

@ -6,8 +6,8 @@ module ActiveRecord
module Tasks # :nodoc:
class PostgreSQLDatabaseTasks # :nodoc:
DEFAULT_ENCODING = ENV["CHARSET"] || "utf8"
ON_ERROR_STOP_1 = "ON_ERROR_STOP=1".freeze
SQL_COMMENT_BEGIN = "--".freeze
ON_ERROR_STOP_1 = "ON_ERROR_STOP=1"
SQL_COMMENT_BEGIN = "--"
delegate :connection, :establish_connection, :clear_active_connections!,
to: ActiveRecord::Base

@ -93,7 +93,7 @@ def add_gem_filter
return if gems_paths.empty?
gems_regexp = %r{(#{gems_paths.join('|')})/(bundler/)?gems/([^/]+)-([\w.]+)/(.*)}
gems_result = '\3 (\4) \5'.freeze
gems_result = '\3 (\4) \5'
add_filter { |line| line.sub(gems_regexp, gems_result) }
end

@ -4,6 +4,6 @@ class LoadError
# 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$/, "".freeze) == path.to_s.sub(/\.rb$/, "".freeze)
location.sub(/\.rb$/, "") == path.to_s.sub(/\.rb$/, "")
end
end

@ -20,7 +20,7 @@ class String
# Technically, it looks for the least indented non-empty line
# in the whole string, and removes that amount of leading whitespace.
def strip_heredoc
gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "".freeze).tap do |stripped|
gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "").tap do |stripped|
stripped.freeze if frozen?
end
end

@ -144,7 +144,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("::".freeze)
constants << ([namespace, suffix] - ["Object"]).join("::")
end
end
constants
@ -410,7 +410,7 @@ def loadable_constants_for_path(path, bases = autoload_paths)
next unless expanded_path.start_with?(expanded_root)
root_size = expanded_root.size
next if expanded_path[root_size] != ?/.freeze
next if expanded_path[root_size] != ?/
nesting = expanded_path[(root_size + 1)..-1]
paths << nesting.camelize unless nesting.blank?
@ -505,7 +505,7 @@ def load_missing_constant(from_mod, const_name)
if file_path
expanded = File.expand_path(file_path)
expanded.sub!(/\.rb\z/, "".freeze)
expanded.sub!(/\.rb\z/, "")
if loading.include?(expanded)
raise "Circular dependency detected while autoloading constant #{qualified_name}"

@ -13,8 +13,8 @@ class ISO8601Parser # :nodoc:
class ParsingError < ::ArgumentError; end
PERIOD_OR_COMMA = /\.|,/
PERIOD = ".".freeze
COMMA = ",".freeze
PERIOD = "."
COMMA = ","
SIGN_MARKER = /\A\-|\+|/
DATE_MARKER = /P/

@ -14,7 +14,7 @@ def initialize(duration, precision: nil)
# Builds and returns output string.
def serialize
parts, sign = normalize
return "PT0S".freeze if parts.empty?
return "PT0S" if parts.empty?
output = +"P"
output << "#{parts[:years]}Y" if parts.key?(:years)

@ -73,7 +73,7 @@ def camelize(term, uppercase_first_letter = true)
string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase }
end
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
string.gsub!("/".freeze, "::".freeze)
string.gsub!("/", "::")
string
end
@ -90,11 +90,11 @@ def camelize(term, uppercase_first_letter = true)
# camelize(underscore('SSLError')) # => "SslError"
def underscore(camel_cased_word)
return camel_cased_word unless /[A-Z-]|::/.match?(camel_cased_word)
word = camel_cased_word.to_s.gsub("::".freeze, "/".freeze)
word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_'.freeze }#{$2.downcase}" }
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2'.freeze)
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2'.freeze)
word.tr!("-".freeze, "_".freeze)
word = camel_cased_word.to_s.gsub("::", "/")
word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_' }#{$2.downcase}" }
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
word.tr!("-", "_")
word.downcase!
word
end
@ -130,11 +130,11 @@ def humanize(lower_case_and_underscored_word, capitalize: true, keep_id_suffix:
inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
result.sub!(/\A_+/, "".freeze)
result.sub!(/\A_+/, "")
unless keep_id_suffix
result.sub!(/_id\z/, "".freeze)
result.sub!(/_id\z/, "")
end
result.tr!("_".freeze, " ".freeze)
result.tr!("_", " ")
result.gsub!(/([a-z\d]*)/i) do |match|
"#{inflections.acronyms[match.downcase] || match.downcase}"
@ -199,14 +199,14 @@ def tableize(class_name)
# classify('calculus') # => "Calculus"
def classify(table_name)
# strip out any leading schema name
camelize(singularize(table_name.to_s.sub(/.*\./, "".freeze)))
camelize(singularize(table_name.to_s.sub(/.*\./, "")))
end
# Replaces underscores with dashes in the string.
#
# dasherize('puni_puni') # => "puni-puni"
def dasherize(underscored_word)
underscored_word.tr("_".freeze, "-".freeze)
underscored_word.tr("_", "-")
end
# Removes the module part from the expression in the string.
@ -269,7 +269,7 @@ def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
# NameError is raised when the name is not in CamelCase or the constant is
# unknown.
def constantize(camel_cased_word)
names = camel_cased_word.split("::".freeze)
names = camel_cased_word.split("::")
# Trigger a built-in NameError exception including the ill-formed constant in the message.
Object.const_get(camel_cased_word) if names.empty?
@ -364,7 +364,7 @@ def ordinalize(number)
# const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?"
# const_regexp("::") # => "::"
def const_regexp(camel_cased_word)
parts = camel_cased_word.split("::".freeze)
parts = camel_cased_word.split("::")
return Regexp.escape(camel_cased_word) if parts.blank?

@ -58,7 +58,7 @@ module Inflector
# I18n.locale = :de
# transliterate('Jürgen')
# # => "Juergen"
def transliterate(string, replacement = "?".freeze)
def transliterate(string, replacement = "?")
raise ArgumentError, "Can only transliterate strings. Received #{string.class.name}" unless string.is_a?(String)
I18n.transliterate(
@ -97,7 +97,7 @@ def parameterize(string, separator: "-", preserve_case: false)
parameterized_string.gsub!(/[^a-z0-9\-_]+/i, separator)
unless separator.nil? || separator.empty?
if separator == "-".freeze
if separator == "-"
re_duplicate_separator = /-{2,}/
re_leading_trailing_separator = /^-|-$/i
else
@ -108,7 +108,7 @@ def parameterize(string, separator: "-", preserve_case: false)
# No more than one of the separator in a row.
parameterized_string.gsub!(re_duplicate_separator, separator)
# Remove leading/trailing separator.
parameterized_string.gsub!(re_leading_trailing_separator, "".freeze)
parameterized_string.gsub!(re_leading_trailing_separator, "")
end
parameterized_string.downcase! unless preserve_case

@ -182,7 +182,7 @@ def _encrypt(value, **metadata_options)
def _decrypt(encrypted_message, purpose)
cipher = new_cipher
encrypted_data, iv, auth_tag = encrypted_message.split("--".freeze).map { |v| ::Base64.strict_decode64(v) }
encrypted_data, iv, auth_tag = encrypted_message.split("--").map { |v| ::Base64.strict_decode64(v) }
# Currently the OpenSSL bindings do not raise an error if auth_tag is
# truncated, which would allow an attacker to easily forge it. See

@ -122,7 +122,7 @@ def initialize(secret, options = {})
def valid_message?(signed_message)
return if signed_message.nil? || !signed_message.valid_encoding? || signed_message.blank?
data, digest = signed_message.split("--".freeze)
data, digest = signed_message.split("--")
data.present? && digest.present? && ActiveSupport::SecurityUtils.secure_compare(digest, generate_digest(data))
end
@ -150,7 +150,7 @@ def valid_message?(signed_message)
def verified(signed_message, purpose: nil, **)
if valid_message?(signed_message)
begin
data = signed_message.split("--".freeze)[0]
data = signed_message.split("--")[0]
message = Messages::Metadata.verify(decode(data), purpose)
@serializer.load(message) if message
rescue ArgumentError => argument_error

@ -15,7 +15,7 @@ def convert
end
rounded_number = NumberToRoundedConverter.convert(number, options)
format.gsub("%n".freeze, rounded_number).gsub("%u".freeze, options[:unit])
format.gsub("%n", rounded_number).gsub("%u", options[:unit])
end
private

@ -14,7 +14,7 @@ def convert
private
def parts
left, right = number.to_s.split(".".freeze)
left, right = number.to_s.split(".")
left.gsub!(delimiter_pattern) do |digit_to_delimit|
"#{digit_to_delimit}#{options[:delimiter]}"
end

@ -25,7 +25,7 @@ def convert # :nodoc:
rounded_number = NumberToRoundedConverter.convert(number, options)
unit = determine_unit(units, exponent)
format.gsub("%n".freeze, rounded_number).gsub("%u".freeze, unit).strip
format.gsub("%n", rounded_number).gsub("%u", unit).strip
end
private

@ -22,7 +22,7 @@ def convert
human_size = number / (base**exponent)
number_to_format = NumberToRoundedConverter.convert(human_size, options)
end
conversion_format.gsub("%n".freeze, number_to_format).gsub("%u".freeze, unit)
conversion_format.gsub("%n", number_to_format).gsub("%u", unit)
end
private

@ -7,7 +7,7 @@ class NumberToPercentageConverter < NumberConverter # :nodoc:
def convert
rounded_number = NumberToRoundedConverter.convert(number, options)
options[:format].gsub("%n".freeze, rounded_number)
options[:format].gsub("%n", rounded_number)
end
end
end

@ -20,9 +20,9 @@ def convert
formatted_string =
if BigDecimal === rounded_number && rounded_number.finite?
s = rounded_number.to_s("F")
s << "0".freeze * precision
a, b = s.split(".".freeze, 2)
a << ".".freeze
s << "0" * precision
a, b = s.split(".", 2)
a << "."
a << b[0, precision]
else
"%00.#{precision}f" % rounded_number

@ -92,7 +92,7 @@ def finish(name, id, payload)
event.finish!
event.payload.merge!(payload)
method = name.split(".".freeze).first
method = name.split(".").first
send(method, event)
end

@ -46,7 +46,7 @@ def clear_tags!
def current_tags
# We use our object ID here to avoid conflicting with other instances
thread_key = @thread_key ||= "activesupport_tagged_logging_tags:#{object_id}".freeze
thread_key = @thread_key ||= "activesupport_tagged_logging_tags:#{object_id}"
Thread.current[thread_key] ||= []
end

@ -43,8 +43,8 @@ def self.name
"Time"
end
PRECISIONS = Hash.new { |h, n| h[n] = "%FT%T.%#{n}N".freeze }
PRECISIONS[0] = "%FT%T".freeze
PRECISIONS = Hash.new { |h, n| h[n] = "%FT%T.%#{n}N" }
PRECISIONS[0] = "%FT%T"
include Comparable, DateAndTime::Compatibility
attr_reader :time_zone
@ -147,7 +147,7 @@ def inspect
#
# Time.zone.now.xmlschema # => "2014-12-04T11:02:37-05:00"
def xmlschema(fraction_digits = 0)
"#{time.strftime(PRECISIONS[fraction_digits.to_i])}#{formatted_offset(true, 'Z'.freeze)}"
"#{time.strftime(PRECISIONS[fraction_digits.to_i])}#{formatted_offset(true, 'Z')}"
end
alias_method :iso8601, :xmlschema
alias_method :rfc3339, :xmlschema

@ -18,7 +18,7 @@ module ActiveSupport
module XmlMini_JDOM #:nodoc:
extend self
CONTENT_KEY = "__content__".freeze
CONTENT_KEY = "__content__"
NODE_TYPE_NAMES = %w{ATTRIBUTE_NODE CDATA_SECTION_NODE COMMENT_NODE DOCUMENT_FRAGMENT_NODE
DOCUMENT_NODE DOCUMENT_TYPE_NODE ELEMENT_NODE ENTITY_NODE ENTITY_REFERENCE_NODE NOTATION_NODE

@ -34,7 +34,7 @@ def to_hash
end
module Node #:nodoc:
CONTENT_ROOT = "__content__".freeze
CONTENT_ROOT = "__content__"
# Convert XML document to hash.
#

@ -13,8 +13,8 @@ module XmlMini_LibXMLSAX #:nodoc:
class HashBuilder
include LibXML::XML::SaxParser::Callbacks
CONTENT_KEY = "__content__".freeze
HASH_SIZE_KEY = "__hash_size__".freeze
CONTENT_KEY = "__content__"
HASH_SIZE_KEY = "__hash_size__"
attr_reader :hash

@ -38,7 +38,7 @@ def to_hash
end
module Node #:nodoc:
CONTENT_ROOT = "__content__".freeze
CONTENT_ROOT = "__content__"
# Convert XML document to hash.
#

@ -16,8 +16,8 @@ module XmlMini_NokogiriSAX #:nodoc:
# Class that will build the hash while the XML document
# is being parsed using SAX events.
class HashBuilder < Nokogiri::XML::SAX::Document
CONTENT_KEY = "__content__".freeze
HASH_SIZE_KEY = "__hash_size__".freeze
CONTENT_KEY = "__content__"
HASH_SIZE_KEY = "__hash_size__"
attr_reader :hash

@ -8,7 +8,7 @@ module ActiveSupport
module XmlMini_REXML #:nodoc:
extend self
CONTENT_KEY = "__content__".freeze
CONTENT_KEY = "__content__"
# Parse an XML Document string or IO into a simple hash.
#

@ -248,7 +248,7 @@ def test_string_to_time_does_not_preserve_time_zone
def test_string_to_time_frozen_preserves_timezone
with_preserve_timezone(true) do
with_env_tz "US/Eastern" do
source = "2016-04-23T15:11:12+01:00".freeze
source = "2016-04-23T15:11:12+01:00"
time = source.to_time
assert_instance_of Time, time
@ -262,7 +262,7 @@ def test_string_to_time_frozen_preserves_timezone
def test_string_to_time_frozen_does_not_preserve_time_zone
with_preserve_timezone(false) do
with_env_tz "US/Eastern" do
source = "2016-04-23T15:11:12+01:00".freeze
source = "2016-04-23T15:11:12+01:00"
time = source.to_time
assert_instance_of Time, time

Some files were not shown because too many files have changed in this diff Show More