Class: Mutations::BooleanFilter

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

Constant Summary collapse

BOOL_MAP =
{"true" => true, "1" => true, "false" => false, "0" => false}

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



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/mutations/boolean_filter.rb', line 9

def filter(data)

  # Handle nil case
  if data.nil?
    return [nil, nil] if options[:nils]
    return [nil, :nils]
  end
  
  # Now check if it's empty:
  return [data, :empty] if data == ""

  # If data is true or false, we win.
  return [data, nil] if data == true || data == false

  # If data is an Integer, like 1, let's convert it to a string first
  data = data.to_s if data.is_a?(Integer)

  # If data's a string, try to convert it to a boolean. If we can't, it's invalid.
  if data.is_a?(String)
    res = BOOL_MAP[data.downcase]
    return [res, nil] unless res.nil?
    return [data, :boolean]
  else
    return [data, :boolean]
  end
end