Class: Goliath::Rack::Validation::RequiredValue
- Inherits:
-
Object
- Object
- Goliath::Rack::Validation::RequiredValue
- Includes:
- Goliath::Rack::Validator
- Defined in:
- lib/goliath/rack/validation/required_value.rb
Overview
Middleware to validate that a given parameter has a specified value.
Instance Attribute Summary collapse
-
#key ⇒ Object
readonly
Returns the value of attribute key.
-
#values ⇒ Object
readonly
Returns the value of attribute values.
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, opts = {}) ⇒ Goliath::Rack::Validation::RequiredValue
constructor
Creates the Goliath::Rack::Validation::RequiredValue validator.
- #value_valid?(params) ⇒ Boolean
Methods included from Goliath::Rack::Validator
Constructor Details
#initialize(app, opts = {}) ⇒ Goliath::Rack::Validation::RequiredValue
Creates the Goliath::Rack::Validation::RequiredValue validator.
24 25 26 27 28 |
# File 'lib/goliath/rack/validation/required_value.rb', line 24 def initialize(app, opts = {}) @app = app @key = opts[:key] || 'id' @values = [opts[:values]].flatten end |
Instance Attribute Details
#key ⇒ Object (readonly)
Returns the value of attribute key.
15 16 17 |
# File 'lib/goliath/rack/validation/required_value.rb', line 15 def key @key end |
#values ⇒ Object (readonly)
Returns the value of attribute values.
15 16 17 |
# File 'lib/goliath/rack/validation/required_value.rb', line 15 def values @values end |
Instance Method Details
#call(env) ⇒ Object
30 31 32 33 |
# File 'lib/goliath/rack/validation/required_value.rb', line 30 def call(env) return validation_error(400, "Provided #{@key} is invalid") unless value_valid?(env['params']) @app.call(env) end |
#value_valid?(params) ⇒ Boolean
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/goliath/rack/validation/required_value.rb', line 35 def value_valid?(params) if !params.has_key?(key) || params[key].nil? || (params[key].is_a?(String) && params[key] =~ /^\s*$/) return false end if params[key].is_a?(Array) return false if params[key].empty? params[key].each { |k| return false unless values.include?(k) } elsif !values.include?(params[key]) return false end true end |