嵌套模块和实例级方法

时间:2013-08-13 18:42:55

标签: ruby-on-rails ruby module instance

假设我有

module A
  include module B

  class C
    def methodC
      B.methodB
    end
    def self.methodD 
      somemethod
    end
  end
end

module B
  def self.methodB
    A::C.methodD
  end    
end

instance = A::C.new

如何避免使用此类级别方法(自我)?实际上,我如何在methodB上致电instance

2 个答案:

答案 0 :(得分:1)

如果我很好理解,在某个方法中调用当前实例的关键字是self。所以你可以使用

def methodC
     self.methodB
end

并删除self内的self.methodB

(顺便说一句,除非methodD必须在class C内找到,否则您可以将其放在moduleB内,然后删除A::C的{​​{1}};))

答案 1 :(得分:0)

试试这个

# define moduke B first so that, it can be included in A
module B
  def methodB
    A::C.methodD
  end
end

module A

  class C
    include B # include B here  

    def methodC
      methodB
    end

    def self.methodD 
      somemethod
    end
  end
end

instance = A::C.new
p instance.methods.grep /methodB/
=> [:methodB]