module

2020-06-27  本文已影响0人  SecondRocker

module(模块),主要两大功能:
1、提供命名空间
2、 Mix-in 扩展功能(模块混入)
特性:
1、不能拥有实例
2、不能被继承

一些用法:


module Animal
   def run
     puts 'run'
   end
end

module AnimalExt
  def run
    puts 'ext run'
  end

  def self.included(base) # 钩子,在被include时触发,base为include他的类
      base.extend ClassMethods #为类方法
  end

  module ClassMethods
    def eat
        puts 'eat'
    end
  end
end
class Rabbit
  include Animal #扩展实例方法
  include AnimalExt # 实例方法优先级更高
  extend Animal #扩展类方法
end
Rabbit.ancestors #[Rabbit, AnimalExt, Animal, Object, Kernel, BasicObject]  最后混入的在前面,查找方法时顺序查找
Animal.eat #获得的类方法

module X
  module_function
  def ha
    puts 'ha'
  end
end
X.ha #直接调用模块的方法

module Z
  extend self
  def e
    puts 'e'
  end
end
Z.e  # 混入自己的方法变为“类”方法

拓展
Active::Support是rails对模块混入的一个扩展,解决依赖问题;主要解读参考:利用ActiveSupport::Concern来组织你需要include的module

上一篇下一篇

猜你喜欢

热点阅读