Class: Goliath::Rack::Validation::NumericRange

Inherits:
Object
  • Object
show all
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.

Examples:

use Goliath::Rack::Validation::NumericRange, {:key => 'num', :min => 1, :max => 30, :default => 10}
use Goliath::Rack::Validation::NumericRange, {:key => 'num', :min => 1.2, :max => 3.5, :default => 2.9, :as => Float}
use Goliath::Rack::Validation::NumericRange, {:key => 'num', :min => 1}
use Goliath::Rack::Validation::NumericRange, {:key => 'num', :max => 10}

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ Goliath::Rack::Validation::NumericRange

Called by the framework to create the Goliath::Rack::Validation::NumericRange validator

Parameters:

  • app

    The app object

  • opts (Hash) (defaults to: {})

    The options hash

Options Hash (opts):

  • :key (String)

    The key to look for in the parameters

  • :min (Integer)

    The minimum value

  • :max (Integer)

    The maximum value

  • :as (Class)

    How to convert: Float will use .to_f, Integer (the default) will use .to_i

  • :default (Integer)

    The default to set if outside the range

Raises:

  • (Exception)


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

#call(env) ⇒ Object



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

#coerce(val) ⇒ Object



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

#valueObject



62
63
64
# File 'lib/goliath/rack/validation/numeric_range.rb', line 62

def value
  @default || @min || @max
end