From c230ee066654b70aca205b00810da2074f73263f Mon Sep 17 00:00:00 2001 From: Ryan McGeary Date: Sun, 23 Feb 2025 20:04:04 -0700 Subject: [PATCH] Optimize string allocation during mutation --- lib/strip_attributes.rb | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/lib/strip_attributes.rb b/lib/strip_attributes.rb index ced2dd1..013a1de 100644 --- a/lib/strip_attributes.rb +++ b/lib/strip_attributes.rb @@ -1,4 +1,3 @@ -# frozen_string_literal: true require "active_model" module ActiveModel::Validations::HelperMethods @@ -56,28 +55,28 @@ def self.strip_record(record, options = {}) def self.strip_string(value, options = {}) return value unless value.is_a?(String) - value = value.dup allow_empty = options[:allow_empty] collapse_spaces = options[:collapse_spaces] replace_newlines = options[:replace_newlines] regex = options[:regex] - value = value.gsub(regex, "") if regex + value = value.dup + value.gsub!(regex, "") if regex - value = if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_SPACE) - value.gsub(MULTIBYTE_SPACE_AT_ENDS, "") + if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_SPACE) + value.gsub!(MULTIBYTE_SPACE_AT_ENDS, "") else - value.strip + value.strip! end - value = value.gsub(NEWLINES, " ") if replace_newlines + value.gsub!(NEWLINES, " ") if replace_newlines if collapse_spaces - value = if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_BLANK) - value.gsub(MULTIBYTE_BLANK_REPEATED, " ") + if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_BLANK) + value.gsub!(MULTIBYTE_BLANK_REPEATED, " ") else - value.squeeze(" ") + value.squeeze!(" ") end end