我已经使用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
我在测试示例中省略了它,因为无论是否有结果都是相同的。
有人可以帮忙吗?非常感谢。
答案 0 :(得分:2)
您只需将密钥定义为:
key :my_name, ACustomType
而不是:
key :my_name, type: ACustomType
key
的方法签名为def key(name, type, options = {})