我已经使用 MongoMapper 几个星期了,并且喜欢它的很多功能。最吸引人的功能之一是能够定义自定义键类型和验证方法(请参阅此页面上的“自定义类型”:http: //mongomapper.com/documentation/types.html)。
但是,我尝试通过一个小测试使用它们,并且在我的情况下验证方法没有触发。这是代码:
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
这是我的结果:
#<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!">]
我知道“写问题”问题,并使用https://github.com/mongomapper/mongomapper/issues/507上的解决方案对其进行了修补。这是代码:
# 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
我从我的测试示例中省略了它,因为无论有没有它,结果都是一样的。
任何人都可以帮忙吗?非常感谢。