有一個共同的成語說。它利用included
對象模型鉤子。每次將模塊包含到模塊/類中時,都會調用此鉤子
module MyExtensions
def self.included(base)
# base is our target class. Invoke `extend` on it and pass nested module with class methods.
base.extend ClassMethods
end
def mod1
"mod1"
end
module ClassMethods
def mod2
"mod2"
end
end
end
class Testing
include MyExtensions
end
t = Testing.new
puts t.mod1
puts Testing::mod2
# >> mod1
# >> mod2
我個人喜歡將實例方法組合到一個嵌套模塊中。據我所知,這是不太被人接受的做法。
module MyExtensions
def self.included(base)
base.extend ClassMethods
base.include(InstanceMethods)
# or this, if you have an old ruby and the line above doesn't work
# base.send :include, InstanceMethods
end
module InstanceMethods
def mod1
"mod1"
end
end
module ClassMethods
def mod2
"mod2"
end
end
end
感謝您清除了這一點給我。清除描述性信息。非常感謝您花時間。 – 2013-05-13 15:23:30
請參閱我的答案,對此進行相當簡潔的簡化。 :) – Magne 2017-11-27 11:53:26