Extracting code to a module, failed

Dear all,

I wrote a piece of code with which I can copy models and their
associated models as new database entries. Now I want to extract this
code so I can easily use it in other projects/models.
What I have:

class Foo < ActiveRecord::Base
cattr_accessor :non_duplicatable_columns
self.non_duplicatable_columns = [self.primary_key, ‘created_at’,
‘updated_at’,‘created_on’, ‘updated_on’] + self.column_names.select {|
column_name| column_name =~ /_id$/}

def copy
copy_columns = self.column_names - non_duplicatable_columns
a = Hash.new
copy_columns.each {|cc| a[cc] = self.send(cc) }
clone = self.create(a)

Naively I thought I could copy-past this code in a module called
Duplicatable and include that in Foo. This does not work. Ruby tells
me that the file duplicatable.rb should define Duplicatable. Weird but
I figured out that commenting out everything outside the def copy
block makes it work. However now I lost the cattr_accessor and the
initialisation of the non_duplicatable_columns.

I can place these two lines in an def init … end but that requires
me to do both the include Duplicatable and a call to init. Isn’t there
a nicer way of doing it?

With kind regards,

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs