[英]Module extend and class_eval in ruby
我正在測試元編程,我有一個案例,我不明白:
module Bar
def self.append_features klass
klass.class_eval do
def self.a
puts 'a'
end
end
end
end
class Foo
extend Bar
end
在哪里定義“a”方法? 因為:
Foo.new.a,Foo.a和Class.a不起作用!
如果我在Foo類中使用include而不是extend,方法“a”是為Foo定義的(Foo.a可以工作),我想:如果“self”為include = Class,“self”為extend = Metaclass,但是沒有。
可以解釋方法“a”在哪里?
append_features
是ruby中的一個鈎子方法,當你include Bar
時,它被調用。 現在它將類方法a
添加到類Bar
,然后它將類方法a
給Foo
。
讓我來解釋一下你這個方法怎么a
成為類方法Bar
。 當你include Bar
,會調用hook方法,並將其參數klass
設置為Bar
。 現在klass.class_eval {..}
class_eval
一套self
塊內{..}
為Bar
。 現在def self.a;puts 'a';end
意味着def Bar.a;puts 'a';end
。
module Bar
def self.append_features klass
klass.class_eval do
def self.a
puts 'a'
end
end
end
end
class Foo
include Bar
end
Foo.a # => a
在哪里定義“a”方法? 因為:Foo.new.a,Foo.a和Class.a不起作用!
這是因為你確實extend Bar
,它沒有調用hook方法append_features
。 所以類方法a
尚未在類Bar
定義,正如您所期望的那樣。
“當這個模塊包含在另一個,Ruby調用append_features在此模塊中”( 文檔 ) -你extended
酒吧,不included
酒吧。 包含和擴展做了一些不同的事情,除了改變self
的定義 - 例如,他們的鈎子方法是不同的。 我懷疑在您extend
Bar的情況下,根本不會調用append_features
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.