Skip to content
Browse files

Added option to disable the dynamic fields in documents

Use self.forbid_dynamic_fields in the model to forbid dynamic fields or use self.allow_dynamic_fields = false like in Mongoid.
  • Loading branch information...
1 parent 197c2f6 commit 13abf293888e0fe9944e0d5a6badb26405f1c587 @Nucc committed Nov 12, 2012
Showing with 51 additions and 3 deletions.
  1. +19 −3 lib/mongo_mapper/plugins/keys.rb
  2. +32 −0 test/unit/test_keys.rb
View
22 lib/mongo_mapper/plugins/keys.rb
@@ -67,6 +67,22 @@ def load(attrs)
end.allocate.initialize_from_database(attrs)
end
+ def forbid_dynamic_fields
+ self.allow_dynamic_fields = false
+ end
+
+ def allow_dynamic_fields
+ self.allow_dynamic_fields = true
+ end
+
+ def allow_dynamic_fields=(value)
+ @allow_dynamic_fields = value
+ end
+
+ def allow_dynamic_fields?
+ @allow_dynamic_fields.nil? || @allow_dynamic_fields
+ end
+
private
def key_accessors_module_defined?
if method(:const_defined?).arity == 1 # Ruby 1.9 compat check
@@ -182,10 +198,10 @@ def attributes=(attrs)
return if attrs == nil or attrs.blank?
attrs.each_pair do |key, value|
- if respond_to?(:"#{key}=")
- self.send(:"#{key}=", value)
- else
+ if !respond_to?(:"#{key}=") and self.class.allow_dynamic_fields?
self[key] = value
+ else
+ self.send(:"#{key}=", value)
end
end
end
View
32 test/unit/test_keys.rb
@@ -86,4 +86,36 @@ def user=(user)
instance.value.should == nil
end
end
+
+ context "forbid dynamic elements" do
+ setup do
+ options = ["self.forbid_dynamic_fields", "self.allow_dynamic_fields = false"]
+ @documents = []
+ options.each do |option|
+ @documents << Class.new do
+ include MongoMapper::Document
+ class_eval option
+ key :valid, String
+ end
+ end
+ end
+
+ should "throw NoMethodError when it wants to initialize non-existent key" do
+ @documents.each do |doc|
+ lambda{ doc.new(:age => 21) }.should raise_error(NoMethodError)
+ end
+ end
+
+ should "throw NoMethodError when it wants to assign value to non-existent key" do
+ @documents.each do |doc|
+ lambda{ doc.new.age = "21" }.should raise_error(NoMethodError)
+ end
+ end
+
+ should "not throw exception when key exists" do
+ @documents.each do |doc|
+ lambda{ doc.new.valid = "Valid" }.should_not raise_error
+ end
+ end
+ end
end # KeyTest

0 comments on commit 13abf29

Please sign in to comment.
Something went wrong with that request. Please try again.