gpt4 book ai didi

ruby - MongoMapper:多组键和方法的组合?

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:29 26 4
gpt4 key购买 nike

在 MongoMapper 中,类可以从父类(super class)继承键和方法。在这里,我编写了包含整数键“baz”的代码,以及将其实例的 baz 值设置为连续计数的朴素排序方法。

require 'mongo_mapper'
require './init/mongo_init' # Load database connection

class Sortable
include MongoMapper::Document
key :baz, Integer

def self.sort_baz
counter = 0
Sortable.each do |record|
record.baz = counter
counter += 1
record.save
end
end
end

class Model < Sortable
include MongoMapper::Document
key :foo, String
key :bar, String
end

Model.delete_all
model1 = Model.new.save
model2 = Model.new.save
model3 = Model.new.save
Model.sort_baz
Model.all.each do |record|
puts record.inspect
end

结果如下:

#<Model _id: BSON::ObjectId('525ecd73ab48655daa000001'), _type: "Model", baz: 0>
#<Model _id: BSON::ObjectId('525ecd73ab48655daa000002'), _type: "Model", baz: 1>
#<Model _id: BSON::ObjectId('525ecd73ab48655daa000003'), _type: "Model", baz: 2>

这是我的问题:我正在编写代码,其中包含希望继承多种功能的模型,在 Ruby 中建议使用模块和包含,因为 Ruby 不支持多重继承。

但是MongoMapper文档必须是类,而不是模块。换句话说,这是我想做的,但行不通:

module Sortable
include MongoMapper::Document
key :baz, Integer

def self.sort_baz
counter = 0
self.each do |record|
record.baz = counter
counter += 1
record.save
end
end
end

module OtherFunctionality
include MongoMapper::Document
key :bam, Integer
end

class Model
include MongoMapper::Document
key :foo, String
key :bar, String
include Sortable
include OtherFunctionality
end

是否有任何方法可以根据具体情况干净地组合多组可重用的 MongoMapper 键和类方法?

最佳答案

这对我有用——感谢@muistooshort

module Sortable
def self.included(base)

base.class_exec do
include MongoMapper::Document
key :baz, Integer

def self.sort_baz
counter = 0
self.each do |record|
record.baz = counter
counter += 1
record.save
end
end
end

end
end

class Model
include MongoMapper::Document
key :foo, String
key :bar, String
include Sortable
end

关于ruby - MongoMapper:多组键和方法的组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19410279/

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