Skip to content
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

Use frozen string literals and regex constants to reduce allocations #63

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
10 changes: 7 additions & 3 deletions lib/strip_attributes.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# frozen_string_literal: true
require "active_model"

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

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

if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_SPACE)
value.gsub!(/\A#{MULTIBYTE_SPACE}+|#{MULTIBYTE_SPACE}+\z/, "")
value.gsub!(MULTIBYTE_SPACE_AT_ENDS, "")
else
value.strip!
end

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

if collapse_spaces
if MULTIBYTE_SUPPORTED && Encoding.compatible?(value, MULTIBYTE_BLANK)
value.gsub!(/#{MULTIBYTE_BLANK}+/, " ")
value.gsub!(MULTIBYTE_BLANK_REPEATED, " ")
else
value.squeeze!(" ")
end
Expand Down