Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

allow trusted hash attributes to be mass assigned

  • Loading branch information...
commit 1e5599fb993675c203cb32250548d8c00555f7d9 1 parent 145b77b
@ryanb authored
View
3  lib/trusted_params/active_record_additions.rb
@@ -2,13 +2,12 @@ module TrustedParams
module ActiveRecordAdditions
def self.included(base)
base.extend(ClassMethods)
- base.attr_accessible nil
end
def remove_attributes_protected_from_mass_assignment(attributes)
unless self.class.accessible_attributes.include? "all"
attributes.each do |key, value|
- unless self.class.accessible_attributes.include? key.to_s
+ unless self.class.accessible_attributes.include?(key.to_s) || attributes.trusted?(key)
raise ActiveRecord::UnavailableAttributeAssignmentError, "attribute \"#{key}\" is protected from mass assignment"
end
end
View
5 lib/trusted_params/hash_additions.rb
@@ -4,16 +4,17 @@ def trust(*attribute_names)
if attribute_names.empty?
@trusted_attributes = :all
else
- @trusted_attributes = attribute_names
+ @trusted_attributes = attribute_names.map(&:to_sym)
attribute_names.each do |attribute_name|
self[attribute_name].trust if self[attribute_name].kind_of? Hash
end
end
+ self
end
def trusted?(attribute_name)
if defined?(@trusted_attributes)
- @trusted_attributes == :all || @trusted_attributes.include?(attribute_name)
+ @trusted_attributes == :all || @trusted_attributes.include?(attribute_name.to_sym)
end
end
end
View
9 spec/trusted_params/active_record_additions_spec.rb
@@ -23,8 +23,13 @@
it "should be able to mass assign specific attributes" do
MockedModel.attr_accessible :name
- user = MockedModel.new(:name => "foo")
- user.name.should == "foo"
+ m = MockedModel.new(:name => "foo")
+ m.name.should == "foo"
lambda { MockedModel.new(:content => "foo") }.should raise_error(ActiveRecord::UnavailableAttributeAssignmentError)
end
+
+ it "should be able to mass assign with trusted hash" do
+ m = MockedModel.new({:name => "foo"}.trust)
+ m.name.should == "foo"
+ end
end
View
11 spec/trusted_params/hash_additions_spec.rb
@@ -33,4 +33,15 @@
@hash.should be_trusted(:child)
@hash[:child].should be_trusted(:boing)
end
+
+ it "should return hash from trust method" do
+ @hash.trust.should == @hash
+ end
+
+ it "should be indifferent between string and symbol" do
+ @hash.trust("foo")
+ @hash.should be_trusted(:foo)
+ @hash.trust(:bar)
+ @hash.should be_trusted("bar")
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.