Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Forbid dynamic fields like in Mongoid #476

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 19 additions & 3 deletions lib/mongo_mapper/plugins/keys.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
32 changes: 32 additions & 0 deletions test/unit/test_keys.rb
Expand Up @@ -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