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}
use Goliath::Rack::Validation::NumericRange, {:key => 'num', :max => 10}

Instance Method Summary (collapse)

Constructor Details

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

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

Parameters:

  • app

    The app object

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

    The options hash

Options Hash (opts):

  • (String) :key

    The key to look for in the parameters

  • (Integer) :min

    The minimum value

  • (Integer) :max

    The maximum value

  • (Integer) :default

    The default to set if outside the range

Raises:

  • (Exception)


23
24
25
26
27
28
29
30
31
32
33
# File 'lib/goliath/rack/validation/numeric_range.rb', line 23

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?

  @default = opts[:default]
end

Instance Method Details

- (Object) call(env)



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/goliath/rack/validation/numeric_range.rb', line 35

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] = env['params'][@key].to_i

    if (!@min.nil? && env['params'][@key] < @min) || (!@max.nil? && env['params'][@key] > @max)
      env['params'][@key] = value
    end
  end

  @app.call(env)
end

- (Object) value



53
54
55
# File 'lib/goliath/rack/validation/numeric_range.rb', line 53

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