cin
cin

Reputation: 155

include a Module to a class with a class Method referencing to the Module to be included

I have the following example

class Test
  configure_helper
end

module ConfigureHelper
  module ClassMethods
    def configure_helper
    end
  end
end

ConfigureHelper has some more functionality which will extend the class with ClassMethods in which the module was included.

So the problem is, if i use the following code to include the module

Test.send :include, ConfigureHelper

The Test class will be loaded and will raise a NoMethodError for configure_helper.

Is there any way to attach the configure_helper method so that configure_helper wont be called?

Upvotes: 0

Views: 141

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

Why not include the module right in the class definition?

module ConfigureHelper
  def self.included base
    base.extend ClassMethods
  end

  module ClassMethods
    def configure_helper
    end
  end
end

class Test
  include ConfigureHelper

  configure_helper
end

Upvotes: 1

Shamith c
Shamith c

Reputation: 3739

Try it

  class Test
    end

    module ConfigureHelper
      module ClassMethods
       def self.included(base)
         base.class_eval do
           def configure_helper
              p 'Yes'
           end
         end
       end
      end
    end


    Test.send(:include, ConfigureHelper::ClassMethods)

    Test.new.configure_helper

Upvotes: 0

Related Questions