# Extracting code to a module, failed

**URL:** <https://www.ruby-forum.com/t/extracting-code-to-a-module-failed/123163>\
**Category:** Rails\
**Created:** [December 14, 2007, 3:53pm UTC](https://www.ruby-forum.com/t/extracting-code-to-a-module-failed/123163 "2007-12-14T15:53:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![harm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/b4bc9f/32.png) [@harm](https://www.ruby-forum.com/u/harm)\
**Post date:** [December 14, 2007, 3:53pm UTC](https://www.ruby-forum.com/t/extracting-code-to-a-module-failed/123163/1 "2007-12-14T15:53:15Z")

</div>

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)  
end  
end

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,  
Harm
