Class: Mutations::StringFilter

Inherits:
AdditionalFilter show all
Defined in:
lib/mutations/string_filter.rb

Instance Attribute Summary

Attributes inherited from InputFilter

#options

Instance Method Summary collapse

Methods inherited from AdditionalFilter

inherited

Methods inherited from InputFilter

#default, default_options, #discard_empty?, #discard_invalid?, #discard_nils?, #has_default?, #initialize

Constructor Details

This class inherits a constructor from Mutations::InputFilter

Instance Method Details

#filter(data) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mutations/string_filter.rb', line 17

def filter(data)
  # Handle nil case
  if data.nil?
    return [nil, nil] if options[:nils]
    return [nil, :nils]
  end

  # At this point, data is not nil. If it's not a string, convert it to a string for some standard classes
  data = data.to_s if !options[:strict] && [TrueClass, FalseClass, Integer, Float, BigDecimal, Symbol].any? { |klass| data.is_a?(klass) }

  # Now ensure it's a string:
  return [data, :string] unless data.is_a?(String)

  # At this point, data is a string. Now remove control characters from the string:
  data = data.gsub(/((?=[[:cntrl:]])[^\t\r\n])+/, ' ') unless options[:allow_control_characters]

  # Transform it using strip:
  data = data.strip if options[:strip]

  # Now check if it's blank:
  if data == ""
    if options[:empty_is_nil]
      return [nil, (:nils unless options[:nils])]
    elsif options[:empty]
      return [data, nil]
    else
      return [data, :empty]
    end
  end

  # Now check to see if it's the correct size:
  return [data, :min_length] if options[:min_length] && data.length < options[:min_length]
  return [data, :max_length] if options[:max_length] && data.length > options[:max_length]

  # Ensure it match
  return [data, :in] if options[:in] && !options[:in].include?(data)

  # Ensure it matches the regexp
  return [data, :matches] if options[:matches] && (options[:matches] !~ data)

  # We win, it's valid!
  [data, nil]
end