Permalink
Browse files

Correctly clean hashes with indifferent access.

  • Loading branch information...
1 parent 11f0081 commit b3993e8b09730a094ea85a3badbe0c0968e990eb @drewolson committed Apr 10, 2012
Showing with 34 additions and 7 deletions.
  1. +5 −3 lib/params_cleaner.rb
  2. +29 −4 spec/params_cleaner_spec.rb
View
@@ -1,5 +1,6 @@
require "active_support/concern"
require "active_support/core_ext/hash/slice"
+require "active_support/hash_with_indifferent_access"
module ParamsCleaner
extend ActiveSupport::Concern
@@ -8,15 +9,16 @@ module ParamsCleaner
def clean_params(root_params = params)
cleaned_params = root_params.map do |key, val|
- if val.is_a?(Hash)
- clean_values = clean_params(val.slice(*self.class._allowed_params[key]))
+ if val.kind_of?(Hash)
+ clean_values = clean_params(val.slice(*self.class._allowed_params[key.to_sym]))
[key, clean_values]
else
[key, val]
end
end
- Hash[cleaned_params]
+ cleaned_params_hash = Hash[cleaned_params]
+ HashWithIndifferentAccess.new(cleaned_params_hash)
end
module ClassMethods
@@ -28,8 +28,33 @@ def params
instance = klass.new
instance.clean_params[:root].should == {
- :foo => "foo",
- :bar => "bar"
+ "foo" => "foo",
+ "bar" => "bar"
+ }
+ end
+
+ it "handles hashes with indifferent_access" do
+ klass = Class.new do
+ include ParamsCleaner
+
+ allowed_params :root => [:foo, :bar]
+
+ def params
+ HashWithIndifferentAccess.new(
+ :root => HashWithIndifferentAccess.new(
+ :foo => "foo",
+ :bar => "bar",
+ :baz => "baz"
+ )
+ )
+ end
+ end
+
+ instance = klass.new
+
+ instance.clean_params[:root].should == {
+ "foo" => "foo",
+ "bar" => "bar"
}
end
@@ -58,8 +83,8 @@ def params
instance = klass.new
instance.clean_params[:root][:foo].should == {
- :a => 1,
- :b => 2
+ "a" => 1,
+ "b" => 2
}
end
end

0 comments on commit b3993e8

Please sign in to comment.