Method: StripAttributes.strip_string

Defined in:
lib/strip_attributes.rb

.strip_string(value, options = {}) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/strip_attributes.rb', line 53

def self.strip_string(value, options = {})
  return value unless value.is_a?(String)
  # TODO: FUTURE CHANGE: return value if value.frozen?

  allow_empty      = options[:allow_empty]
  collapse_spaces  = options[:collapse_spaces]
  replace_newlines = options[:replace_newlines]
  regex            = options[:regex]

  value = value.dup
  value.gsub!(regex, "") if regex

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

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

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

  (value.blank? && !allow_empty) ? nil : value
end