引用模块和加载库(extend,include,require,load )

通常引用模块有以下3种情况:

1.在类定义中引入模块,使模块中的方法成为类的实例方法

这种情况是最常见的

直接 include 即可

2.在类定义中引入模块,使模块中的方法成为类的类方法

这种情况也是比较常见的

直接 extend 即可

3.在类定义中引入模块,既希望引入实例方法,也希望引入类方法

这个时候需要使用 include,

但是在模块中对类方法的定义有不同,定义出现在self.included块中

def self.included(c) ... end 中。

module Base  

  def show  

    puts "You came here!"  

  end  

 

  #扩展类方法  

  def self.included(base)  

    def base.call  

      puts "I'm strong!"  

    end  

    base.extend(ClassMethods)  

  end  

 

  #类方法  

  module ClassMethods  

    def hello  

      puts "Hello baby!"  

    end  

   end  

end  

class Bus  

  include Base  

end 

Bus.new.show  

Bus.call  

Bus.hello 

Require:

require方法让你加载一个库(一般用于导入类库),并且只加载一次,如果你多次加载会返回false。只有当你要加载的库位于一个分离的文件中时才有必要使用require。使用时不需要加扩展名,一般放在文件的最前面:

    require ‘test_library’

Load:

load可以执行代码和用来多次加载一个库,你必须指定扩展名:

   load ‘test_library.rb’

Include:

当你的库加载之后,你可以在你的类定义中包含一个module,让module的实例方法和变量成为类本身的实例方法和类变量,它们mix进来了。根据锄头书,include并不会把module的实例方法拷贝到类中,只是做了引用,包含module的不同类都指向了同一个对象。如果你改变了module的定义,即使你的程序还在运行,所有包含module的类都会改变行为。

   module Log 
       def class_type 
           “This class is of type: #{self.class}” 
       end 
   end 
   class TestClass 
       include Log 
   end 
   tc=TestClass.new.class_type    #=>This class is of type: TestClass

Extend:

extend会把module的实例方法作为类方法加入类中:

   module Log 
       def class_type 
           “This class is of type: #{self.class}” 
       end 
   end 
   class TestClass 
       extend Log 
   end 
   tc=TestClass.class_type       #=>This class is of type: TestClass

原文地址:https://www.cnblogs.com/qinyan20/p/3654755.html