views:

37

answers:

1

If I write this, everything works fine:

class A < ActiveRecord::Base
acts_as_taggable
end

But if I take acts_as_taggable and put it into a module that class A includes, I get an error:

module B
  def self.included(base)
    base.class_eval do
      extend ClassMethods
      include InstanceMethods
    end
  end

  module ClassMethods
    acts_as_taggable
  end

  module InstanceMethods
  end
end

class A < ActiveRecord::Base
include B

The error from the code above is:

undefined local variable or method `acts_as_taggable' for C::ClassMethods:Module

Is it not correct to call acts_as_taggable from an included module?

Does it need to be in the class definition itself?

+3  A: 

When Ruby loads the file containing your module B and reaches the acts_as_taggable line, it will try to execute the acts_as_taggable class method of ClassMethods (which doesn't exist because it is actually a class method of ActiveRecord::Base).

You can use the included method to call acts_as_taggable when your module is included though. included is passed the class the module is being included in, so the following will work:

module B
  def self.included(base)
    base.acts_as_taggable

    # ...
  end

  # ...
end
Phil Ross