27
转载关于Ruby的extend和include
Ruby extend and include
from URL: http://www.rsa.idv.tw/?p=151
Ruby modules有兩種方式mixed into a class,讓class可以簡易新增行為
- include
- extend
- extend through include pattern
通常用來新增Instance of mehtod
module CMath def add(n) self + n end end Fixnum.class_eval do include CMath end puts 3.add 10
通常用來新增class method
module ExtendMe def v_object_id “my object id is #{self.object_id}” end end class Person extend ExtendMe end puts Person.v_object_id
提供統一介面處理
module ExtendThroughIncludePattern def self.included(klass) klass.extend ClassMethods end def instance_method “this is an instance of #{self.class}” end module ClassMethods def class_method “this is a method of the #{self} class” end end end class Person include ExtendThroughIncludePattern end puts Person.new.instance_method puts Person.class_method
self.included
Callback invoked whenever the receiver is included in another module or class. This should be used in preference to Module.append_features if your code wants to perform some action when a module is included in another.


