lib/goliath/rack/validation/required_value.rb in goliath-0.9.1 vs lib/goliath/rack/validation/required_value.rb in goliath-0.9.2
- old
+ new
@@ -1,6 +1,6 @@
-require 'goliath/rack/validation_error'
+require 'goliath/rack/validator'
module Goliath
module Rack
module Validation
# Middleware to validate that a given parameter has a specified value.
@@ -8,10 +8,12 @@
# @example
# use Goliath::Rack::Validation::RequiredValue, {:key => 'mode', :values => %w(foo bar)}
# use Goliath::Rack::Validation::RequiredValue, {:key => 'baz', :values => 'awesome'}
#
class RequiredValue
+ include Goliath::Rack::Validator
+
attr_reader :key, :values
# Creates the Goliath::Rack::Validation::RequiredValue validator.
#
# @param app The app object
@@ -24,34 +26,28 @@
@key = opts[:key] || 'id'
@values = [opts[:values]].flatten
end
def call(env)
- value_valid!(env['params'])
+ return validation_error(400, "Provided #{@key} is invalid") unless value_valid?(env['params'])
@app.call(env)
end
- def value_valid!(params)
- error = false
+ def value_valid?(params)
if !params.has_key?(key) || params[key].nil? ||
(params[key].is_a?(String) && params[key] =~ /^\s*$/)
- error = true
+ return false
end
if params[key].is_a?(Array)
- error = true if params[key].empty?
+ return false if params[key].empty?
+ params[key].each { |k| return false unless values.include?(k) }
- params[key].each do |k|
- unless values.include?(k)
- error = true
- break
- end
- end
elsif !values.include?(params[key])
- error = true
+ return false
end
- raise Goliath::Validation::Error.new(400, "Provided #{@key} is invalid") if error
+ true
end
end
end
end
end
\ No newline at end of file