Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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...
commit 13abf293888e0fe9944e0d5a6badb26405f1c587 1 parent 197c2f6
Laszlo Papp authored

Showing 2 changed files with 51 additions and 3 deletions. Show diff stats Hide diff stats

  1. +19 3 lib/mongo_mapper/plugins/keys.rb
  2. +32 0 test/unit/test_keys.rb
22 lib/mongo_mapper/plugins/keys.rb
@@ -67,6 +67,22 @@ def load(attrs)
67 67 end.allocate.initialize_from_database(attrs)
68 68 end
69 69
  70 + def forbid_dynamic_fields
  71 + self.allow_dynamic_fields = false
  72 + end
  73 +
  74 + def allow_dynamic_fields
  75 + self.allow_dynamic_fields = true
  76 + end
  77 +
  78 + def allow_dynamic_fields=(value)
  79 + @allow_dynamic_fields = value
  80 + end
  81 +
  82 + def allow_dynamic_fields?
  83 + @allow_dynamic_fields.nil? || @allow_dynamic_fields
  84 + end
  85 +
70 86 private
71 87 def key_accessors_module_defined?
72 88 if method(:const_defined?).arity == 1 # Ruby 1.9 compat check
@@ -182,10 +198,10 @@ def attributes=(attrs)
182 198 return if attrs == nil or attrs.blank?
183 199
184 200 attrs.each_pair do |key, value|
185   - if respond_to?(:"#{key}=")
186   - self.send(:"#{key}=", value)
187   - else
  201 + if !respond_to?(:"#{key}=") and self.class.allow_dynamic_fields?
188 202 self[key] = value
  203 + else
  204 + self.send(:"#{key}=", value)
189 205 end
190 206 end
191 207 end
32 test/unit/test_keys.rb
@@ -86,4 +86,36 @@ def user=(user)
86 86 instance.value.should == nil
87 87 end
88 88 end
  89 +
  90 + context "forbid dynamic elements" do
  91 + setup do
  92 + options = ["self.forbid_dynamic_fields", "self.allow_dynamic_fields = false"]
  93 + @documents = []
  94 + options.each do |option|
  95 + @documents << Class.new do
  96 + include MongoMapper::Document
  97 + class_eval option
  98 + key :valid, String
  99 + end
  100 + end
  101 + end
  102 +
  103 + should "throw NoMethodError when it wants to initialize non-existent key" do
  104 + @documents.each do |doc|
  105 + lambda{ doc.new(:age => 21) }.should raise_error(NoMethodError)
  106 + end
  107 + end
  108 +
  109 + should "throw NoMethodError when it wants to assign value to non-existent key" do
  110 + @documents.each do |doc|
  111 + lambda{ doc.new.age = "21" }.should raise_error(NoMethodError)
  112 + end
  113 + end
  114 +
  115 + should "not throw exception when key exists" do
  116 + @documents.each do |doc|
  117 + lambda{ doc.new.valid = "Valid" }.should_not raise_error
  118 + end
  119 + end
  120 + end
89 121 end # KeyTest

0 comments on commit 13abf29

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