Error moving act_as_taggable to an included module

If I write this, everything will work well:

class A < ActiveRecord::Base
acts_as_taggable
end

But if I take it acts_as_taggableand put it in a module that includes class A, I get an error message:

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 above code:

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

Is it wrong to call acts_as_taggablefrom an included module?

Do I need to be in the class definition itself?

+3
source share
1 answer

When Ruby loads the file containing your module Band reaches the line acts_as_taggable, it will try to execute the class method of the acts_as_taggableclass ClassMethods(which is not, because it is actually a class method ActiveRecord::Base).

included acts_as_taggable, . included , , :

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

    # ...
  end

  # ...
end
+5

Source: https://habr.com/ru/post/1722519/


All Articles