質問

In MongoMapper, classes can inherit keys and methods from superclasses. Here I've written code to include an integer key "baz", and a naive sorting method to set its instances' baz values to sequential counting numbers.

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

Here are the results:

#<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>

Here's my question: I'm writing code with models that will want to inherit multiple types of functionalities, which in Ruby would suggest using Modules and includes, since Ruby doesn't support multiple inheritance.

But MongoMapper documents have to be classes, not modules. In other words, this is what I'd like to do, but it won't work:

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

Is there any way to cleanly combine multiple reusable sets of MongoMapper keys and class methods on a case-by-case basis?

役に立ちましたか?

解決

This worked for me– thanks to @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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top