DataMapper类中的Ruby重用方法(helper)

时间:2010-03-10 17:39:53

标签: ruby datamapper

我正在尝试重用DataMapper类中的方法。这可能也是我认为的一个红宝石问题。

class Foo
  include DataMapper::Resource

  property :name
  property ...

  def self.special_name
    self.all(:name => 'whatever')
  end
end

class Bar
  include DataMapper::Resource

  property :name
  property ...

  def self.special_name
    self.all(:name => 'whatever')
  end
end

所以方法special_name将用于两个类,因为我想得到相同的结果。但它也使用像“all”这样的DataMapper方法。那你怎么做呢?

THX

3 个答案:

答案 0 :(得分:0)


module SpecialName

property :name def self.special_name self.all(:name => 'whatever') end end

class Foo include DataMapper::Resource include SpecialName end

class Bar include DataMapper::Resource include SpecialName end

答案 1 :(得分:0)

module SpecialName
  def self.included(base)
    base.property :name, String
    base.extend ClassMethods
  end

  module ClassMethods
    def special_name
      all(:name => 'whatever')
    end
  end
end

class Foo
  include DataMapper::Resource
  include SpecialName
end

有关此include / extend惯用法的更多信息,请参阅http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/

答案 2 :(得分:0)

“回答”是错误的。有关详细信息,请参阅此问题的答案:How to extend DataMapper::Resource with custom method

简短版本:您需要使用DataMapper的内置扩展器,因为记录/行和模型/表具有不同的类。

DataMapper::Model.append_extensions(MyModule::ClassMethods) #Add to model
DataMapper::Model.append_inclusions(MyModule::InstanceMethods) #Add to record