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

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

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

Parameters:

  • app

    The app object

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

    The options to create the validator with

Options Hash (opts):

  • :key (String)

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

  • :values (String | Array)

    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

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
end

#valuesObject (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

#call(env) ⇒ Object



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

#value_valid!(params) ⇒ Object



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