Skip to content

Commit 1903208

Browse files
authored
Merge pull request #80 from rmm5t/optimize-string-mutation
Optimize string allocation during mutation
2 parents 4702b05 + c230ee0 commit 1903208

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

lib/strip_attributes.rb

+9-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# frozen_string_literal: true
21
require "active_model"
32

43
module ActiveModel::Validations::HelperMethods
@@ -56,28 +55,28 @@ def self.strip_record(record, options = {})
5655

5756
def self.strip_string(value, options = {})
5857
return value unless value.is_a?(String)
59-
value = value.dup
6058

6159
allow_empty = options[:allow_empty]
6260
collapse_spaces = options[:collapse_spaces]
6361
replace_newlines = options[:replace_newlines]
6462
regex = options[:regex]
6563

66-
value = value.gsub(regex, "") if regex
64+
value = value.dup
65+
value.gsub!(regex, "") if regex
6766

68-
value = if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_SPACE)
69-
value.gsub(MULTIBYTE_SPACE_AT_ENDS, "")
67+
if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_SPACE)
68+
value.gsub!(MULTIBYTE_SPACE_AT_ENDS, "")
7069
else
71-
value.strip
70+
value.strip!
7271
end
7372

74-
value = value.gsub(NEWLINES, " ") if replace_newlines
73+
value.gsub!(NEWLINES, " ") if replace_newlines
7574

7675
if collapse_spaces
77-
value = if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_BLANK)
78-
value.gsub(MULTIBYTE_BLANK_REPEATED, " ")
76+
if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_BLANK)
77+
value.gsub!(MULTIBYTE_BLANK_REPEATED, " ")
7978
else
80-
value.squeeze(" ")
79+
value.squeeze!(" ")
8180
end
8281
end
8382

0 commit comments

Comments
 (0)