有可能增加方法到使用模塊的類。例如,
class Test
include Singleton
end
號這並不 「添加方法一類」。 include
只是使Singleton
的超類Test
。而已。沒有什麼是「添加到課堂」的。這只是繼承。
是否可以使用相同的方法?例如,
class Test
include Singleton
def test
include Instructions_to_add_to_the_method
puts 'done'
end
end
沒有方法Test#include
,因此這將只是一個raise
NoMethodError
。
當調用Test.instance.test
,我想:
hi !
done
這就是繼承是:
class Test
include Singleton
def test
super
puts 'done'
end
end
module Instructions_to_add_to_the_method
def test
puts 'hi'
end
end
class Test
include Instructions_to_add_to_the_method
end
Test.instance.test
# hi
# done
注意在Ruby中使用繼承的方式是有點落後。如果你真的需要這樣的東西,你應該使用Beta這樣的語言,這是繼承如何自然發揮作用。
更好的解決方案會是這樣的Template Method Software Design Pattern它在紅寶石可以像yield
簡單荷蘭國際集團以一個塊的內容:
class Test
include Singleton
def test
yield
puts 'done'
end
end
Test.instance.test { puts 'hi' }
# hi
# done
或採取Proc
作爲參數:
class Test
include Singleton
def test(prc)
prc.()
puts 'done'
end
end
Test.instance.test(-> { puts 'hi' })
# hi
# done
或通過調用掛鉤方法:
class Test
include Singleton
def test
extension_hook
puts 'done'
end
def extension_hook; end
end
class HookedTest < Test
def extension_hook
puts 'hi'
end
end
HookedTest.instance.test
# hi
# done
我不想調用另一種方法,因爲它會給我變量的範圍帶來問題。
代碼中沒有變量,所以不可能有任何「問題」與他們。
不,這不是紅寶石的工作原理。模塊不是宏。如果這就是你想要實現的目標,你可以使用'Module#prepend'或'Module#include'與'super'結合使用? –