title: Rails 3: Use 'before_create' within a module (for ActiveRecord models)
body: <p>I am writing an application where many (but not all) ActiveRecord models have a <code>hash</code> column. This is populated on creation with a random MD5 hash, and used for referencing a single object instead of its ID. To achieve this, I have included the following module in the respective models, and use <code>find_by_id_or_hash!()</code> in all controllers instead of <code>find</code>:</p>
  
  <pre><code>module IdOrHashFindable
  
    def self.included(base)
      base.extend(ClassMethods)
    end
  
    module ClassMethods
  
      before_create :create_hash             ## &lt;-- THIS FAILS
  
      # legacy. in use only until find by ID is phased out altogether
      def find_by_id_or_hash!(id_or_hash)
        id_or_hash.to_s.size &gt;= 32 ? find_by_hash!(id_or_hash) : find(id_or_hash)
      end
    end
  
    def to_param; self.hash end
    def create_hash; self.hash = Support.create_hash  end
  
  end
  </code></pre>
  
  <p>To keep things DRY, I would like to have the <code>before_create</code> call also inside the module. However, I keep getting either</p>
  
  <pre><code>undefined method `before_create' for IdOrHashFindable:Module
  </code></pre>
  
  <p>or</p>
  
  <pre><code>undefined method `before_create' for IdOrHashFindable::ClassMethods:Module
  </code></pre>
  
  <p>depending where I put it. This makes sense (after all, I am calling a function, not defining it), but I'd still like to know how this can be done. (I cannot overwrite <code>before_create</code> since there are other <code>before_create</code> invocations).</p>
  
  <p>Also, for all models which have this module included, quite similar tests apply. How do I consistently test this feature? Do I write a custom <code>describe ... end</code> block and <code>require</code> it into each <code>model_spec.rb</code> where it applies? How do I pass the correct model to use without resorting to global variables?</p>
  
  <p>Any ideas would be appreciated!</p>