Ruby reuse methods in DataMapper classes (helper)
-
19-09-2019 - |
Question
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
Solution
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/.
OTHER TIPS
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
The "answer" is wrong. See the answer to this questions for more info: How to extend DataMapper::Resource with custom method
Short version: You need to use DataMapper's built-in extenders because a record/row and a model/table have different classes.
DataMapper::Model.append_extensions(MyModule::ClassMethods) #Add to model
DataMapper::Model.append_inclusions(MyModule::InstanceMethods) #Add to record