lib/parameters/param.rb in parameters-0.2.0 vs lib/parameters/param.rb in parameters-0.2.1

- old
+ new

@@ -34,10 +34,11 @@ protected # Type classes and their coercion methods TYPE_COERSION = { + Hash => :coerce_hash, Set => :coerce_set, Array => :coerce_array, URI => :coerce_uri, Regexp => :coerce_regexp, DateTime => :coerce_date, @@ -50,12 +51,13 @@ } # # Coerces a given value into a specific type. # - # @param [Class] type - # The type to coerce the value into. + # @param [Class, Proc] type + # The type to coerce the value into. If a Proc is given, it will be + # called with the value to coerce. # # @param [Object] value # The value to coerce. # # @return [Object] @@ -64,22 +66,38 @@ # @since 0.2.0 # def coerce_type(type,value) if value.nil? nil + elsif type.kind_of?(Hash) + key_type, value_type = type.entries.first + new_hash = {} + + coerce_hash(Hash,value).each do |key,value| + key = coerce_type(key_type,key) + value = coerce_type(value_type,value) + + new_hash[key] = value + end + + return new_hash elsif type.kind_of?(Set) coerce_array(Array,value).map { |element| - coerce_type(type.first,element) + coerce_type(type.entries.first,element) }.to_set elsif type.kind_of?(Array) coerce_array(Array,value).map do |element| - coerce_type(type.first,element) + coerce_type(type.entries.first,element) end + elsif type.kind_of?(Proc) + type.call(value) elsif (method_name = TYPE_COERSION[type]) self.send(method_name,type,value) - else + elsif (type.nil? || type == Object) value + else + type.new(value) end end # # Coerces a given value into the `type` of the param. @@ -92,9 +110,36 @@ # # @since 0.2.0 # def coerce(value) coerce_type(@type,value) + end + + # + # Coerces a given value into a `Hash`. + # + # @param [Hash{Class => Class}] type + # An optional `Set` containing the type to coerce the keys and values + # of the given value to. + # + # @param [Hash, #to_hash, Object] value + # The value to coerce into a `Hash`. + # + # @return [Hash] + # The coerced value. + # + # @since 0.2.1 + # + def coerce_hash(type,value) + if value.kind_of?(Hash) + value + elsif value.kind_of?(Array) + Hash[*value] + elsif value.respond_to?(:to_hash) + value.to_hash + else + {value => true} + end end # # Coerces a given value into a `Set`. #