ruby/datamapper: Refactor class methods to module

Posted by DeSchleib on Stack Overflow See other posts from Stack Overflow or by DeSchleib
Published on 2010-05-24T18:17:36Z Indexed on 2010/05/24 18:21 UTC
Read the original article Hit count: 307

Filed under:
|
|
|

Hello, i've the following code and tried the whole day to refactor the class methods to a sperate module to share the functionality with all of my model classes.

Code (http://pastie.org/974847):

class Merchant
  include DataMapper::Resource

  property :id, Serial                                             
  [...]

  class << self
    @allowed_properties = [:id,:vendor_id, :identifier]

    alias_method :old_get, :get 
    def get *args
      [...]
    end         

    def first_or_create_or_update attr_hash  
      [...]
    end     
  end

end     

I'd like to archive something like:

class Merchant
  include DataMapper::Resource
  include MyClassFunctions
  [...]
end

module MyClassFunctions
  def get [...]
  def first_or_create_or_update[...]
end

=> Merchant.allowed_properties = [:id]
=> Merchant.get( :id=> 1 )

But unfortunately, my ruby skills are to bad. I read a lot of stuff (e.g. here) and now i'm even more confused. I stumbled over the following two points:

  1. alias_method will fail, because it will dynamically defined in the DataMapper::Resource module.
  2. How to get a class method allowed_properties due including a module?

What's the ruby way to go?

Many thanks in advance.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about class