Class: StripParameters::Stripper

Inherits:
Object
  • Object
show all
Defined in:
lib/strip_parameters/stripper.rb

Overview

Singleton that does the actual stripping.

Constant Summary collapse

VALID_OPTIONS =
i[only except if unless allow_empty collapse_spaces replace_newlines regex].freeze
MULTIBYTE_WHITE =

Unicode invisible and whitespace characters. The POSIX character class

:space:

corresponds to the Unicode class Z (“separator”). We also

include the following characters from Unicode class C (“control”), which are spaces or invisible characters that make no sense at the start or end of a string:

U+180E MONGOLIAN VOWEL SEPARATOR
U+200B ZERO WIDTH SPACE
U+200C ZERO WIDTH NON-JOINER
U+200D ZERO WIDTH JOINER
U+2060 WORD JOINER
U+FEFF ZERO WIDTH NO-BREAK SPACE
"\u180E\u200B\u200C\u200D\u2060\uFEFF"
MULTIBYTE_SPACE =
/[[:space:]#{MULTIBYTE_WHITE}]/
MULTIBYTE_SPACE_REGEX =
/\A#{MULTIBYTE_SPACE}+|#{MULTIBYTE_SPACE}+\z/
MULTIBYTE_BLANK =
/[[:blank:]#{MULTIBYTE_WHITE}]/
MULTIBYTE_BLANK_REGEX =
/#{MULTIBYTE_BLANK}+/

Class Method Summary collapse

Class Method Details

.collapse_inner_string_spaces(value) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/strip_parameters/stripper.rb', line 54

def self.collapse_inner_string_spaces(value)
  if Encoding.compatible?(value, MULTIBYTE_BLANK)
    value.gsub!(MULTIBYTE_BLANK_REGEX, " ")
  else
    value.squeeze!(" ")
  end
end

.process_string(value, regex: nil, replace_newlines: false, collapse_spaces: false, allow_empty: false) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/strip_parameters/stripper.rb', line 37

def self.process_string(value, regex: nil, replace_newlines: false, collapse_spaces: false, allow_empty: false)
  value.gsub!(regex, "") if regex
  value.gsub!(/[\r\n]+/, " ") if replace_newlines
  collapse_inner_string_spaces(value) if collapse_spaces
  strip_string(value)

  value if value != "" || allow_empty
end

.strip(paramters, **options) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/strip_parameters/stripper.rb', line 25

def self.strip(paramters, **options)
  paramters.transform_values! do |value|
    if value.is_a?(ActionController::Parameters)
      strip(value, **options)
    else
      next value if !value.is_a?(String) || value.frozen?

      process_string(value, **options)
    end
  end
end

.strip_string(value) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/strip_parameters/stripper.rb', line 46

def self.strip_string(value)
  if Encoding.compatible?(value, MULTIBYTE_SPACE)
    value.gsub!(MULTIBYTE_SPACE_REGEX, "")
  else
    value.strip!
  end
end

.validate_options(options) ⇒ Object

Raises:

  • (ArgumentError)


62
63
64
65
66
67
# File 'lib/strip_parameters/stripper.rb', line 62

def self.validate_options(options)
  keys = options.keys
  return unless (keys - VALID_OPTIONS).any?

  raise ArgumentError, "Unexpected options #{options.keys.inspect}. Valid options are #{VALID_OPTIONS}"
end