Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions lib/mutations/float_filter.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
module Mutations
class FloatFilter < AdditionalFilter
@default_options = {
:nils => false, # true allows an explicit nil to be valid. Overrides any other options
:min => nil, # lowest value, inclusive
:max => nil # highest value, inclusive
:nils => false, # true allows an explicit nil to be valid. Overrides any other options,
:empty_is_nil => false, # if true, treat empty string as if it were nil
:min => nil, # lowest value, inclusive
:max => nil # highest value, inclusive
}

def filter(data)
Expand All @@ -15,7 +16,13 @@ def filter(data)
end

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

# Ensure it's the correct data type (Float)
if !data.is_a?(Float)
Expand Down
13 changes: 13 additions & 0 deletions spec/float_filter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@
assert_equal :empty, errors
end

it "considers empty strings to be nil if empty_is_nil option is used" do
f = Mutations::FloatFilter.new(:empty_is_nil => true)
_filtered, errors = f.filter("")
assert_equal :nils, errors
end

it "returns empty strings as nil if empty_is_nil option is used" do
f = Mutations::FloatFilter.new(:empty_is_nil => true, :nils => true)
filtered, errors = f.filter("")
assert_equal nil, filtered
assert_equal nil, errors
end

it "considers low numbers invalid" do
f = Mutations::FloatFilter.new(:min => 10)
filtered, errors = f.filter(3)
Expand Down