MongoMapper:组成多组键和方法?

时间:2013-10-16 17:48:19

标签: ruby inheritance mongomapper

在MongoMapper中,类可以从超类继承键和方法。在这里,我编写了一个包含整数键“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密钥和类方法?

1 个答案:

答案 0 :(得分:3)

这对我有用 - 感谢@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