访问ruby中的父方法以编写该方法的包装器

时间:2012-10-16 19:33:16

标签: ruby datamapper

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”的值做一些事情。但是上面的实现是错误的,它似乎在循环调用中丢失了。我得到了

.......
.......
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:

我做错了什么?以及如何实现目标

1 个答案:

答案 0 :(得分: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