Skip to content

Commit b7e052e

Browse files
authored
Merge pull request #63 from maxfierke/mf-reduce_allocations
Use frozen string literals and regex constants to reduce allocations
2 parents 07ad134 + e95ef61 commit b7e052e

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

lib/strip_attributes.rb

+7-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# frozen_string_literal: true
12
require "active_model"
23

34
module ActiveModel::Validations::HelperMethods
@@ -27,8 +28,11 @@ module StripAttributes
2728
# U+FEFF ZERO WIDTH NO-BREAK SPACE
2829
MULTIBYTE_WHITE = "\u180E\u200B\u200C\u200D\u2060\uFEFF".freeze
2930
MULTIBYTE_SPACE = /[[:space:]#{MULTIBYTE_WHITE}]/.freeze
31+
MULTIBYTE_SPACE_AT_ENDS = /\A#{MULTIBYTE_SPACE}+|#{MULTIBYTE_SPACE}+\z/.freeze
3032
MULTIBYTE_BLANK = /[[:blank:]#{MULTIBYTE_WHITE}]/.freeze
33+
MULTIBYTE_BLANK_REPEATED = /#{MULTIBYTE_BLANK}+/.freeze
3134
MULTIBYTE_SUPPORTED = "\u0020" == " "
35+
NEWLINES = /[\r\n]+/.freeze
3236

3337
def self.strip(record_or_string, options = {})
3438
if record_or_string.respond_to?(:attributes)
@@ -62,16 +66,16 @@ def self.strip_string(value, options = {})
6266
value.gsub!(regex, "") if regex
6367

6468
if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_SPACE)
65-
value.gsub!(/\A#{MULTIBYTE_SPACE}+|#{MULTIBYTE_SPACE}+\z/, "")
69+
value.gsub!(MULTIBYTE_SPACE_AT_ENDS, "")
6670
else
6771
value.strip!
6872
end
6973

70-
value.gsub!(/[\r\n]+/, " ") if replace_newlines
74+
value.gsub!(NEWLINES, " ") if replace_newlines
7175

7276
if collapse_spaces
7377
if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_BLANK)
74-
value.gsub!(/#{MULTIBYTE_BLANK}+/, " ")
78+
value.gsub!(MULTIBYTE_BLANK_REPEATED, " ")
7579
else
7680
value.squeeze!(" ")
7781
end

0 commit comments

Comments
 (0)