关于模块中include/extend/prepend

by 小赓赓。 at about 9 years ago, last updated at about 9 years ago
W

include

主要用于将一个类插入到一个类或者其他模块。在类中引入模块,使模块中的方法成为类的实例方法

module Management
  def company_notifies
    'company_notifies from management'
  end
end

class User
  include Management
end

user = User.new
puts user.company_notifies

extend

通常在类定义中引入模块,使模块中的方法成为类的类方法时使用

included

当模块被include时会被执行,同时会传递当前作用域的self对象。在类定义中引入模块,既希望引入实例方法,也希望引入类方法这个时候需要使用 include,但是在模块中对类方法的定义有不同,定义出现在方法def self.included(c) ... end 中

module Management
  def self.included base
    puts "Management is being included into #{base}"

    base.include InstanceMethods
    base.extend ClassMethods
  end

  module InstanceMethods
    def company_notifies
      'company_notifies from management'
    end
  end

  module ClassMethods
    def progress
      'progress'
    end
  end

end

class User
  include Management
end

puts '-' * 30
user = User.new
puts user.company_notifies

puts '-' * 30
puts User.progress

prepend 与include区别

  • include把模块注入当前类的继承链后面
  • prepend把模块注入当前类的继承链前面
module Management
  def company_notifies
    'company_notifies from management'
  end
end

class User
  prepend Management
  # include Management

  def company_notifies
    'company_notifies from user'
  end
end

p User.ancestors

puts '-' * 30
user = User.new
puts user.company_notifies
=>[Management, User, Object, Kernel, BasicObject]
# include   =>[User, Management, Object, Kernel, BasicObject]

=>company_notifies from management
# include   =>company_notifies from user