`
gift5168xf
  • 浏览: 28271 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

模块的included()

    博客分类:
  • ROR
阅读更多

    模块的included方法会在其他的类或模块把这个模块混入他们自己里面时被调用,调用时传入的参数为混入模块的模块或类,如下代码

module A
  def A.included(mod)
    puts "#{self} is included in #{mod}"
  end
end

module B
  include A
end


    当B混入A时,此时A的included方法会被调用,通常我们见到的为类设置他的实例方法和类方法的代码如下

module A
  def A.included(mod)  
    def mod.method
      puts "this is the class method"  
    end  
  end  
  def method  
    puts "this is the instance method"  
  end  
end

class B
  include A
end

b=B.new
b.method
B.method


输出结果为:
this is the instance method
this is the class method
当B混入A时,A.included方法被调用,参数为B,该方法中设置了B的method方法,而随着B混入A,A中的实例方法method也作为了B中的实例方法。从而实现了为B同时设置实例方法和类方法
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics