gpt4 book ai didi

ruby - MongoMapper 自定义类型不起作用

转载 作者:可可西里 更新时间:2023-11-01 09:45:15 26 4
gpt4 key购买 nike

我已经使用 MongoMapper 几个星期了,并且喜欢它的很多功能。最吸引人的功能之一是能够定义自定义 key 类型和验证方法(请参阅本页上的“自定义类型”: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

我在我的测试示例中省略了它,因为无论有没有它,结果都是一样的。

有人可以帮忙吗?非常感谢。

最佳答案

您只需要将 key 定义为:

 key :my_name, ACustomType

而不是:

 key :my_name, type: ACustomType

key 的方法签名是 def key(name, type, options = {})

关于ruby - MongoMapper 自定义类型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19391639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com