2013-02-23 41 views
1

我想擴展全部我的Mongoid::Document的實例方法。除了製作模塊並將其包含到每個我想要擴展的Mongoid::Document之外,還應該有其他方法。使用實例方法擴展我所有的Mongoid文檔

例如,對於紅寶石類Array我只想重新討論這一類,並添加我想要的方式:

class Array 
    def my_new_method 
    #.... 
    end 
end 

但我怎麼對於Mongoid::Document

回答

1

如果你要像你一樣打開一類陣列,更好地做到這樣的:

module MyNewMethodable 
    def my_new_method(*args) 
    fail ArgumentError, "not the right number of arguments" 
    #.... 
    rescue => error 
    if MyNewMethodable::Error 
     puts "because then users of your module will know where to look for the fault" 
    else 
     raise error 
    end 
    end 

    class Error < StandardError; end 
    class ArgumentError < Error; end 

end 


class Array 
    include MyNewMethodable 
end 

要爲Mongoid ::文檔

class Mongoid::Document 
    include MyNewMethodable 
end 

但做到這一點,它說here

文檔是Mongoid中的核心對象,任何要堅持到數據庫的對象都必須包含Mongoid ::文件。

所以它已經被包含到您定義的類中。因此,我建議你將你的模塊加入你的課程,而不是Mongoid::Document。例如

class MyClass 
    include Mongoid::Document 
    include MyNewMethodable 
end 
+0

'文檔是Mongoid中的核心對象,任何要被持久化到數據庫的對象都必須包含Mongoid :: Document.'我沒有得到這個。爲什麼我應該做'class MyClass include Mongoid :: Document include MyNewMethodable end'? – 2013-02-24 17:06:51

+0

因爲這就是文檔所說的。我不是一個mongoid用戶,(我不喜歡痛苦;)我的答案是從Ruby的角度來看的,基於文檔,每個文檔都給出了'Mongoid :: Document'類被包含到另一個類中。如果你想混用你自己的方法,那麼經驗法則是把它做到你自己的類,而不是外部類庫,因爲它可能會產生意想不到的後果。 – iain 2013-02-24 17:49:18

2

我會這樣去做

module Mongoid::Document 
    def self.validate 
     ... 
    end 
end 

不過,我想從打開外部模塊避免(即使你這似乎)是在Ruby社區中做一個平常的事。什麼是反對明確包含你自己的模塊?