Class: Goliath::Rack::Validation::RequiredValue

Inherits:
Object
  • Object
show all
Defined in:
lib/goliath/rack/validation/required_value.rb

Overview

Middleware to validate that a given parameter has a specified value.

Examples:

use Goliath::Rack::Validation::RequiredValue, {:key => 'mode', :values => %w(foo bar)}
use Goliath::Rack::Validation::RequiredValue, {:key => 'baz', :values => 'awesome'}

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

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

Creates the Goliath::Rack::Validation::RequiredValue validator.

Parameters:

  • app

    The app object

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

    The options to create the validator with

Options Hash (opts):

  • (String) :key

    The key to look for in params (default: id)

  • (String | Array) :values

    The values to verify are in the params



22
23
24
25
26
# File 'lib/goliath/rack/validation/required_value.rb', line 22

def initialize(app, opts = {})
  @app = app
  @key = opts[:key] || 'id'
  @values = [opts[:values]].flatten
end

Instance Attribute Details

- (Object) key (readonly)

Returns the value of attribute key



13
14
15
# File 'lib/goliath/rack/validation/required_value.rb', line 13

def key
  @key
end

- (Object) values (readonly)

Returns the value of attribute values



13
14
15
# File 'lib/goliath/rack/validation/required_value.rb', line 13

def values
  @values
end

Instance Method Details

- (Object) call(env)



28
29
30
31
# File 'lib/goliath/rack/validation/required_value.rb', line 28

def call(env)
  value_valid!(env['params'])
  @app.call(env)
end

- (Object) value_valid!(params)



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

def value_valid!(params)
  error = false
  if !params.has_key?(key) || params[key].nil? ||
      (params[key].is_a?(String) && params[key] =~ /^\s*$/)
    error = true
  end

  if params[key].is_a?(Array)
    error = true if params[key].empty?

    params[key].each do |k|
      unless values.include?(k)
       error = true
       break
      end
    end
  elsif !values.include?(params[key])
    error = true
  end

  raise Goliath::Validation::Error.new(400, "Provided #{@key} is invalid") if error
end