views:

104

answers:

2

Hi

I'm trying to reuse methods in DataMapper classes. This might be as well a ruby question I think.

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

So the method special_name would be used for both classes as I want to get out the same result. But it also makes use of DataMapper methods like "all". So how would you do this?

Thx

A: 
shingara
I tried that and I get the same thing as for the solution from Greg: "uninitialized constant Foo::SpecialName"
bresc
A: 
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

For more information on this include/extend idiom, see http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/.

Greg Campbell
This doesn't seem to work as I get 'uninitialized constant Foo::SpecialName'
bresc
nevermind my mistake. It works thx
bresc