Class: Goliath::Rack::Validation::NumericRange
- Inherits:
-
Object
- Object
- Goliath::Rack::Validation::NumericRange
- Defined in:
- lib/goliath/rack/validation/numeric_range.rb
Overview
A middleware to validate that a parameter value is within a given range. If the value falls outside the range, or is not provided the default will be used, if provided. If no default the :min or :max values will be applied to the parameter.
Instance Method Summary (collapse)
- - (Object) call(env)
- - (Object) coerce(val)
-
- (Goliath::Rack::Validation::NumericRange) initialize(app, opts = {})
constructor
Called by the framework to create the Goliath::Rack::Validation::NumericRange validator.
- - (Object) value
Constructor Details
- (Goliath::Rack::Validation::NumericRange) initialize(app, opts = {})
Called by the framework to create the Goliath::Rack::Validation::NumericRange validator
25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/goliath/rack/validation/numeric_range.rb', line 25 def initialize(app, opts = {}) @app = app @key = opts[:key] raise Exception.new("NumericRange key required") if @key.nil? @min = opts[:min] @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 |
Instance Method Details
- (Object) call(env)
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/goliath/rack/validation/numeric_range.rb', line 40 def call(env) if !env['params'].has_key?(@key) || env['params'][@key].nil? env['params'][@key] = value else if env['params'][@key].instance_of?(Array) then env['params'][@key] = env['params'][@key].first end env['params'][@key] = coerce(env['params'][@key]) if (!@min.nil? && env['params'][@key] < @min) || (!@max.nil? && env['params'][@key] > @max) env['params'][@key] = value end end @app.call(env) end |
- (Object) coerce(val)
58 59 60 |
# File 'lib/goliath/rack/validation/numeric_range.rb', line 58 def coerce(val) (@coerce_as == Float) ? val.to_f : val.to_i end |
- (Object) value
62 63 64 |
# File 'lib/goliath/rack/validation/numeric_range.rb', line 62 def value @default || @min || @max end |