如何覆盖Ruby DataMapper的create和first_or_create方法?

时间:2013-10-17 17:23:11

标签: ruby overloading datamapper ruby-datamapper

我可以覆盖DataMapper的保存,删除,销毁!使用模块的方法,例如:

require 'data_mapper'

module Record
  def self.included(base)
    base.class_eval do
      include DataMapper::Resource
      property :id, DataMapper::Property::Serial
      alias :parent_save :save
      def save bar 
        # do additional thing with bar
      end
    end
  end
end

class User
  include Record
  property :name,String
end

DataMapper.finalize

# so i could call something like this:
x = User.new
x.name = 'something'
x.save 123 

如果在create上找不到这些方法,如何覆盖first_or_createbase.class_eval do方法?

所以我可以这样说:

User.first_or_create additional_param, name: 'something'

1 个答案:

答案 0 :(得分:1)

您可以通过将类方法添加到class_eval块来覆盖类方法:

class << self
  alias :parent_first_or_create, :first_or_create
  def first_or_create
    # ...
  end

  # do other things with class methods
end