Browse files

adding some basic trust behavior to all hashes

  • Loading branch information...
1 parent ba233aa commit 525c3f2c093cd1b09d50a321bc754cf7aa2fe692 @ryanb committed Jun 1, 2009
Showing with 49 additions and 1 deletion.
  1. +16 −0 lib/trusted_params/hash_additions.rb
  2. +33 −1 spec/trusted_params/hash_additions_spec.rb
View
16 lib/trusted_params/hash_additions.rb
@@ -1,9 +1,25 @@
module TrustedParams
module HashAdditions
+ def trust(*attribute_names)
+ if attribute_names.empty?
+ @trusted_attributes = :all
+ else
+ @trusted_attributes = attribute_names
+ attribute_names.each do |attribute_name|
+ self[attribute_name].trust if self[attribute_name].kind_of? Hash
+ end
+ end
+ end
+ def trusted?(attribute_name)
+ if defined?(@trusted_attributes)
+ @trusted_attributes == :all || @trusted_attributes.include?(attribute_name)
+ end
+ end
end
end
+# I would prefer not setting this in all hashes, but it is the easiest solution at the moment.
class Hash
include TrustedParams::HashAdditions
end
View
34 spec/trusted_params/hash_additions_spec.rb
@@ -1,4 +1,36 @@
-require File.dirname(__FILE__) + '/spec_helper'
+require File.dirname(__FILE__) + '/../spec_helper'
describe Hash do
+ before(:each) do
+ @hash = { :foo => "bar" }
+ end
+
+ it "should not consider attributes trusted by default" do
+ @hash.should_not be_trusted(:foo)
+ end
+
+ it "should trust attributes marked as trusted" do
+ @hash.trust(:foo)
+ @hash.should be_trusted(:foo)
+ end
+
+ it "should trust all attributes when passing no arguments" do
+ @hash.trust
+ @hash.should be_trusted(:foo)
+ @hash.should be_trusted(:anything)
+ end
+
+ it "should trust multiple attributes in one call" do
+ @hash.trust(:foo, :hello)
+ @hash.should be_trusted(:foo)
+ @hash.should be_trusted(:hello)
+ @hash.should_not be_trusted(:anything)
+ end
+
+ it "should inherit trust in nested hashes" do
+ @hash[:child] = { :boing => "bong" }
+ @hash.trust(:child)
+ @hash.should be_trusted(:child)
+ @hash[:child].should be_trusted(:boing)
+ end
end

0 comments on commit 525c3f2

Please sign in to comment.