Sha256: cd4ca4cce53315882d94ee9a7111090b4f020928b9faaf4639163771f24b8a0f

Contents?: true

Size: 950 Bytes

Versions: 6

Compression:

Stored size: 950 Bytes

Contents

module Mutations
  class BooleanFilter < InputFilter
    @default_options = {
      nils: false   # true allows an explicit nil to be valid. Overrides any other options
    }
    
    BOOL_MAP = {"true" => true, "1" => true, "false" => false, "0" => false}
    
    def filter(data)
      
      # Handle nil case
      if data.nil?
        return [nil, nil] if options[:nils]
        return [nil, :nils]
      end
      
      # If data is true or false, we win.
      return [data, nil] if data == true || data == false
      
      # If data is a Fixnum, like 1, let's convert it to a string first
      data = data.to_s if data.is_a?(Fixnum)
      
      # 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
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
mutations-0.5.9 lib/mutations/boolean_filter.rb
mutations-0.5.4 lib/mutations/boolean_filter.rb
mutations-0.5.3 lib/mutations/boolean_filter.rb
mutations-0.5.2 lib/mutations/boolean_filter.rb
mutations-0.5.1 lib/mutations/boolean_filter.rb
mutations-0.5.0 lib/mutations/boolean_filter.rb