lib/permit_params.rb in sinatra-my-params-0.0.3 vs lib/permit_params.rb in sinatra-my-params-0.0.4

- old
+ new

@@ -1,21 +1,24 @@ module PermitParams class InvalidParameterError < StandardError attr_accessor :param, :options end + def permitted_params(params, permitted = {}, strong_validation = false) + return params if permitted.empty? - def permitted_params(params, permitted, strong_validation = false) params.select do |k,v| permitted.keys.map(&:to_s).include?(k.to_s) && !v.nil? && - coerce(v, permitted[k.to_sym], strong_validation) + !coerce(v, permitted[k.to_sym], strong_validation).nil? end end private + Boolean = :boolean + def coerce(param, type, strong = false, options = {}) begin return nil if param.nil? return param if (param.is_a?(type) rescue false) return Integer(param, 10) if type == Integer @@ -24,19 +27,19 @@ return Date.parse(param) if type == Date return Time.parse(param) if type == Time return DateTime.parse(param) if type == DateTime return Array(param.split(options[:delimiter] || ",")) if type == Array return Hash[param.split(options[:delimiter] || ",").map{|c| c.split(options[:separator] || ":")}] if type == Hash - if [TrueClass, FalseClass, Boolean].include? type - coerced = /^(false|f|no|n|0)$/i === param.to_s ? false : /^(true|t|yes|y|1)$/i === param.to_s ? true : nil - raise ArgumentError if coerced.nil? - return coerced - end + return coerce_boolean(param) if [TrueClass, FalseClass, Boolean].include? type return nil rescue ArgumentError - if strong - raise InvalidParameterError, "'#{param}' is not a valid #{type}" - end + raise InvalidParameterError, "'#{param}' is not a valid #{type}" if strong end + end + + def coerce_boolean(param) + coerced = /^(false|f|no|n|0)$/i === param.to_s ? false : /^(true|t|yes|y|1)$/i === param.to_s ? true : nil + raise ArgumentError if coerced.nil? + coerced end end