Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Goliath::Rack::Validation::NumericRange accepts :as => Float -- coerc…
…e param to a float, not an integer
  • Loading branch information
Philip (flip) Kromer committed Apr 18, 2011
1 parent 87e0897 commit 57c5ae1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/goliath/rack/validation/numeric_range.rb
Expand Up @@ -18,6 +18,7 @@ class NumericRange
# @option opts [String] :key The key to look for in the parameters
# @option opts [Integer] :min The minimum value
# @option opts [Integer] :max The maximum value
# @option opts [Class] :as How to convert: Float will use .to_f, Integer (the default) will use .to_i
# @option opts [Integer] :default The default to set if outside the range
# @return [Goliath::Rack::Validation::NumericRange] The validator
def initialize(app, opts = {})
Expand All @@ -29,6 +30,9 @@ def initialize(app, opts = {})
@max = opts[:max]
raise Exception.new("NumericRange requires :min or :max") if @min.nil? && @max.nil?

@coerce_as = opts[:as]
raise Exception.new("NumericRange requires :as to be Float or Integer (default)") unless [nil, Integer, Float].include?(@coerce_as)

@default = opts[:default]
end

Expand All @@ -40,7 +44,7 @@ def call(env)
if env['params'][@key].instance_of?(Array) then
env['params'][@key] = env['params'][@key].first
end
env['params'][@key] = env['params'][@key].to_i
env['params'][@key] = coerce(env['params'][@key])

if (!@min.nil? && env['params'][@key] < @min) || (!@max.nil? && env['params'][@key] > @max)
env['params'][@key] = value
Expand All @@ -50,10 +54,14 @@ def call(env)
@app.call(env)
end

def coerce val
(@coerce_as == Float) ? val.to_f : val.to_i
end

def value
@default || @min || @max
end
end
end
end
end
end
9 changes: 9 additions & 0 deletions spec/unit/rack/validation/numeric_range_spec.rb
Expand Up @@ -58,6 +58,15 @@
end
end


it 'converts to a float with :as => Float' do
@nr = Goliath::Rack::Validation::NumericRange.new(@app, {:key => 'id', :min => -5, :max => 20, :default => 15, :as => Float})
#
@env['params']['id'] = 1.5
@nr.call(@env)
@env['params']['id'].should == 1.5
end

it 'raises error if key is not set' do
lambda { Goliath::Rack::Validation::NumericRange.new('app', {:min => 5}) }.should raise_error
end
Expand Down

0 comments on commit 57c5ae1

Please sign in to comment.