lib/permit_params.rb in sinatra-my-params-0.0.8 vs lib/permit_params.rb in sinatra-my-params-0.0.9

- old
+ new

@@ -9,11 +9,11 @@ return params if permitted.empty? coerced_params = Hash.new({}) params.each do |key, value| - next unless permitted.keys.map(&:to_s).include?(key.to_s) && !value.nil? + next unless permitted?(permitted: permitted, key: key, value: value) coerced = coerce( param: value, type: permitted[key.to_sym], strong_validation: strong_validation, @@ -26,11 +26,16 @@ private Boolean = :boolean Any = :any + Shape = :shape + def permitted?(permitted:, key:, value:) + permitted.keys.map(&:to_s).include?(key.to_s) && !value.nil? + end + def coerce(param:, type:, strong_validation: false, options: {}) return param if type == Any begin return nil if param.nil? @@ -44,10 +49,11 @@ 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, options) if type == Array + return coerce_shape(param, options) if type == Shape return coerce_hash(param, options) if type == Hash return coerce_boolean(param) if [TrueClass, FalseClass, Boolean].include? type nil rescue ArgumentError @@ -62,10 +68,12 @@ def coerce_array(param, options = {}) Array(param.split(options[:delimiter] || ',').map(&:strip)) end def coerce_hash(param, options = {}) + return param if param.is_a?(Hash) + key_value = param.split(options[:delimiter] || ',').map(&:strip).map do |c| c.split(options[:separator] || ':').map(&:strip) end Hash[key_value] end @@ -77,7 +85,18 @@ /^(true|t|yes|y|1)$/i === param.to_s ? true : nil end raise ArgumentError if coerced.nil? coerced + end + + def coerce_shape(param, options = {}) + hash = coerce_hash(param) + has_shape?(hash, options[:shape]) ? hash : nil + end + + def has_shape?(hash, shape) + hash.all? do |k, v| + v.is_a?(Hash) ? has_shape?(v, shape[k]) : shape[k] === v + end end end