2012-10-16 31 views
0
class Package 
    include DataMapper::Resource 
    property :id,   Serial 
    property :product,  String, :required => true 

    def self.create(attributes = {}) 
    puts 'I am in the Object method' 
    #do something here with value of product before creating a new row 
    create(attributes) 
    end 
end 


p = Package.new 
p.create :product=>'myprod' 

我實際上想要一個由Datamapper提供的「create」方法的包裝。所以,在Package表中創建一行之前,我可以用「product」的值做一些事情。但上面的實現是錯誤的,它似乎在通話中丟失。我得到在ruby中訪問父級方法來編寫該方法的包裝

....... 
....... 
I am in the Object method 
I am in the Object method 
I am in the Object method 
I am in the Object method 
I am in the Object method 
I am in the Object method 
I am in the Object method 
I am in the Object method 
I am in the Object method 
SystemStackError - stack level too deep: 

我做錯了什麼?以及如何實現我的目標

回答

4

你在代碼中有什麼是遞歸定義。你必須避免這種情況。

class Package 
    include DataMapper::Resource 
    property :id,   Serial 
    property :product,  String, :required => true 

    def self.create(attributes = {}) 
    puts 'I am in the Object method' 
    #do something here with value of product before creating a new row 
    super(attributes) 
    end 
end 
+0

謝謝@sawa它的工作原理。如果我使用Package.create(......)。但不是如果p = Package.new p.create:product =>'myprod'那麼它說undefined創建方法 – JVK

+0

如果'create'是一個類方法,那麼你只能用它作爲'Package.create',這種情況下代碼是。如果它是一個實例方法,則以「Package.new.create」的形式使用它,在這種情況下,您需要一個不同的定義。你不能這樣做。 – sawa