让一个类include一个模块的几种方法

module Test
  module ClassMethods
    def test_class
      p 'this is a class method'
    end
  end
  
  module InstanceMethods
    def test_ins
      p 'this is a instance method'
    end
    
    def method_missing
      self
    end
  end
  
  # def self.included(receiver)
  #   receiver.extend         ClassMethods
  #   receiver.send :include, InstanceMethods
  # end
end

=begin rdoc
  Add instance methods
=end

# String.class_eval("include Test::InstanceMethods")
# 's'.test_ins # => "this is a instance method"

# String.send :include,Test::InstanceMethods
# 's'.test_ins # => "this is a instance method"

=begin rdoc
  Add class methods
=end

# class << String;include Test::ClassMethods;end
# String.test_class # => "this is a class method"

# String.extend Test::ClassMethods
# String.test_class # => "this is a class method"


从上面的代码可以看出:

class_eval和send :include,Module是一个作用,
都是将一个模块变成self类的实例方法.

class <<和extend是一个作用,
都可以将一个模块变成self的类方法,都把Module的方法塞进了sefl类的metaclass里面.

你可能感兴趣的:(Ruby)