lib/permit_params.rb in sinatra-my-params-0.0.7 vs lib/permit_params.rb in sinatra-my-params-0.0.8
- old
+ new
@@ -9,41 +9,55 @@
return params if permitted.empty?
coerced_params = Hash.new({})
params.each do |key, value|
- if permitted.keys.map(&:to_s).include?(key.to_s) && !value.nil?
- coerced = coerce(value, permitted[key.to_sym], strong_validation, options)
- coerced_params[key] = coerced unless coerced.nil?
- end
+ next unless permitted.keys.map(&:to_s).include?(key.to_s) && !value.nil?
+
+ coerced = coerce(
+ param: value,
+ type: permitted[key.to_sym],
+ strong_validation: strong_validation,
+ options: options
+ )
+ coerced_params[key] = coerced unless coerced.nil?
end
coerced_params
end
private
Boolean = :boolean
Any = :any
- def coerce(param, type, strong_validation = false, options = {})
+ def coerce(param:, type:, strong_validation: false, options: {})
return param if type == Any
begin
return nil if param.nil?
- return param if (param.is_a?(type) rescue false)
- return Integer(param, options[:integer_precision] || 10 ) if type == Integer
+ return param if begin
+ param.is_a?(type)
+ rescue StandardError
+ false
+ end
+ return coerce_integer(param, options) if type == Integer
return Float(param) if type == Float
return String(param) if type == String
return Date.parse(param) if type == Date
return Time.parse(param) if type == Time
return DateTime.parse(param) if type == DateTime
- return coerce_array(param) if type == Array
- return coerce_hash(param) if type == Hash
+ return coerce_array(param, options) if type == Array
+ return coerce_hash(param, options) if type == Hash
return coerce_boolean(param) if [TrueClass, FalseClass, Boolean].include? type
- return nil
+
+ nil
rescue ArgumentError
raise InvalidParameterError, "'#{param}' is not a valid #{type}" if strong_validation
end
+ end
+
+ def coerce_integer(param, options = {})
+ Integer(param, options[:integer_precision] || 10)
end
def coerce_array(param, options = {})
Array(param.split(options[:delimiter] || ',').map(&:strip))
end