I've been using MongoMapper for a couple weeks now and like a lot of its features. One of the most appealing ones is the ability to define custom key types and validation methods (see "Custom Types" on this page: http://mongomapper.com/documentation/types.html).
However, I tried using them with a small test and the validation methods aren't firing in my case. Here's the code:
require 'mongo_mapper'
MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "mmtestdb"
class ACustomType
def self.to_mongo(value)
puts "to_mongo is being called"
"A Safe Value"
end
def self.from_mongo(value)
puts "from_mongo is being called"
"A Safer Value"
end
end
class TestClass
include MongoMapper::Document
key :my_name, type: ACustomType
end
TestClass.delete_all
new_object = TestClass.new
new_object.my_name = "Unsafe Value!"
puts new_object.inspect
new_object.save
puts TestClass.all.inspect
And here are my results:
#<TestClass _id: BSON::ObjectId('525db435ab48651f64000001'), my_name: "Unsafe Value!">
[DEPRECATED] The 'safe' write concern option has been deprecated in favor of 'w'.
[#<TestClass _id: BSON::ObjectId('525db435ab48651f64000001'), my_name: "Unsafe Value!">]
I'm aware of the "write concern" issue and patched it using the solution at https://github.com/mongomapper/mongomapper/issues/507. Here's that code:
# Monkey Patch to solve issue https://github.com/jnunemaker/mongomapper/issues/507
module MongoMapper
module Plugins
module Querying
private
def save_to_collection(options={})
@_new = false
collection.save(to_mongo, :w => options[:safe] ? 1 : 0)
end
end
end
end
I omitted it from my test example because the results are the same with or without it.
Can anyone help? Thanks so much.
You just need to define the key as:
key :my_name, ACustomType
Rather than:
key :my_name, type: ACustomType
key's method signature is def key(name, type, options = {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With