Module#append_features(mod) → mod => When this module is included in another,Ruby calls append_features in this module,passing it the receiving module in mod. Ruby’s default implementation is to add the constants,methods,and module variables of this module to mod if this module has not already been added to mod or one of its ancestors.
Module#prepend_features(mod) → mod => When this module is prepended in another,Ruby calls prepend_features in this module,passing it the receiving module in mod. Ruby’s default implementation is to overlay the constants,and module variables of this module to mod if this module has not already been added to mod or one of its ancestors.
任何人都可以帮助我了解以下问题:
>除了默认值之外,Module的哪些功能被定义为附加和前缀?
>他们的功能差异如何?
>何时使用append_features和prepend_features?
>以上两条粗线之间有什么区别?
解决方法
如您所引用的文字所述:
the constants,and module variables
>他们的功能差异如何?
将混合模块的方法都添加到传递的模块(类)中.区别在于这些方法的查找顺序,如果目标类已经定义了它们:
include的行为就好像目标类继承了mixed-in模块:
module FooBar def say puts "2 - Module" end end class Foo include FooBar def say puts "1 - Implementing Class" super end end Foo.new.say # => # 1 - Implementing Class # 2 - Module
prepend使得混合模块中的方法“更强”,并先执行它们:
module FooBar def say puts "2 - Module" super end end class Foo prepend FooBar def say puts "1 - Implementing Class" end end Foo.new.say # => # 2 - Module # 1 - Implementing Class
这个例子从这里撕下来:http://blog.crowdint.com/2012/11/05/3-killer-features-that-are-coming-on-ruby-2-0.html
>何时使用append_features和prepend_features?
当您想要在方法查找链的末尾保留目标模块(类)的方法时,请使用前端.
通过搜索SO,可以找到一些现实的例子,包括ruby,module和prepend:
> Overriding method by another defined in module
> When monkey patching a method,can you call the overridden method from the new implementation?
> Ruby: Module,Mixins and Blocks confusing?