lib/input_sanitizer/sanitizer.rb in input_sanitizer-0.1.10 vs lib/input_sanitizer/sanitizer.rb in input_sanitizer-0.2.0
- old
+ new
@@ -20,11 +20,14 @@
def cleaned
return @cleaned if @performed
self.class.fields.each do |field, hash|
type = hash[:type]
required = hash[:options][:required]
- clean_field(field, type, required)
+ collection = hash[:options][:collection]
+ namespace = hash[:options][:namespace]
+ default = hash[:options][:default]
+ clean_field(field, type, required, collection, namespace, default)
end
@performed = true
@cleaned.freeze
end
@@ -71,10 +74,21 @@
keys.push(options)
raise "You did not define a converter for a custom type" if converter == nil
self.set_keys_to_type(keys, converter)
end
+ def self.nested(*keys)
+ options = keys.pop
+ sanitizer = options.delete(:sanitizer)
+ keys.push(options)
+ raise "You did not define a sanitizer for nested value" if sanitizer == nil
+ converter = lambda { |value|
+ sanitizer.clean(value)
+ }
+ self.set_keys_to_type(keys, converter)
+ end
+
protected
def self.fields
@fields ||= {}
end
@@ -89,17 +103,19 @@
def self.extract_options(array)
array.last.is_a?(Hash) ? array.last : {}
end
- def clean_field(field, type, required)
+ def clean_field(field, type, required, collection, namespace, default)
if @data.has_key?(field)
begin
- @cleaned[field] = convert(field, type)
+ @cleaned[field] = convert(field, type, collection, namespace)
rescue InputSanitizer::ConversionError => ex
add_error(field, :invalid_value, @data[field], ex.message)
end
+ elsif default
+ @cleaned[field] = converter(type).call(default)
elsif required
add_missing(field)
end
end
@@ -114,11 +130,25 @@
def add_missing(field)
add_error(field, :missing, nil, nil)
end
- def convert(field, type)
- converter(type).call(@data[field])
+ def convert(field, type, collection, namespace)
+ if collection
+ @data[field].map { |v|
+ convert_single(type, v, namespace)
+ }
+ else
+ convert_single(type, @data[field], namespace)
+ end
+ end
+
+ def convert_single(type, value, namespace)
+ if namespace
+ { namespace => converter(type).call(value[namespace]) }
+ else
+ converter(type).call(value)
+ end
end
def converter(type)
type.respond_to?(:call) ? type : self.class.converters[type]
end