有可能增加方法到使用模块的类。例如,
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'结合使用? –