为什么我无法从模块调用父类方法?

时间:2016-02-26 14:41:33

标签: ruby module class-method

这是我的code

module RubyEditExtComponent
    def eventExt
        watchExt "banana"
    end
end

class RubyEditExt
    def self.watchExt(value)
        puts value
    end

    include RubyEditExtComponent
end

RubyEditExt.new.eventExt

我想调用一个特定的(父)类方法,该方法将输出我将传递给它的值。但它说undefined method watchExt

我哪里错了?

2 个答案:

答案 0 :(得分:1)

从实例方法调用

watchExt,因此它应该是一个实例方法本身:

class RubyEditExt
  def watchExt(value) # NO self
    puts value
  end
  ...
end

或者它应该被称为类方法:

module RubyEditExtComponent
  def eventExt
    self.class.watchExt "banana"
  end
end

答案 1 :(得分:1)

可能是,您要尝试的是使用模块RubyEditExt中的功能扩展您的类RubyEditExtComponent。这与继承无关(ChildClass< ParentClass)。通常,您将执行此操作以模块化功能,从而保持您的类清洁并且模块可重用。这些模块称为mixins。

请参阅下面的示例。这样,您可以使用实例方法扩展您的类,您可以为类的每个对象调用这些方法,或者为包含该模块的类定义类方法。

module RubyEditExtComponent
  def self.included(klass)
    klass.instance_eval do
      include InstanceMethods
      extend ClassMethods
    end
  end

  module InstanceMethods
    def eventExt
      watchExt "banana"
    end
  end

  module ClassMethods
    def eventExt2
      self.new.watchExt "banana"
    end
  end
end

class RubyEditExt
  include RubyEditExtComponent

  def watchExt(value)
    puts value
  end
end

方法self.included在包含模块(include RubyEditExtComponent)时被调用,它接收包含它的类。现在,您可以为类的对象调用实例方法:

RubyEditExt.new.eventExt
banana
 => nil

或者你调用类方法。在这个方法中,我创建了一个包含模块(self.new)的类的实例(self == RubyEditExt),然后为它调用实例方法watchExt

RubyEditExt.eventExt2
banana
=> nil