From the Module
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, methods, and module variables of this module to mod if this module has not already been added to mod or one of its ancestors.
Can anyone help me to understand the below questions:
What more features of
Module
are defined asappend
andprepend
except those default?How they differ functionally?
When to use
append_features
and whenprepend_features
?what is the difference between two bold lines as above?
I thought to add it as a comment to a good answer which @Mladen Jablanovic has already made but I couldn't due to my low reputation point.
I've found a more concise, clearer and more descriptive answer on a post here - Ruby modules: Include vs Prepend vs Extend and I post it here just in case someone needs it and could get it with less effort.
Direct quotes:
I would suggest reading the post to get a better understanding as it comes with examples.
As specified in the text you quoted:
Both add methods of the mixed-in module to the passed module (class). The difference is in the lookup order of these methods, in case that the target class already has them defined:
include
behaves as if the target class inherited mixed-in module:prepend
makes the methods from the mixed in module "stronger" and executes them first:The example kindly ripped off from here: http://blog.crowdint.com/2012/11/05/3-killer-features-that-are-coming-on-ruby-2-0.html
Use
prepend
when you want to keep methods of the target module (class) at the end of the method lookup chain.Some real-world examples can be found by searching SO for
ruby
,module
andprepend
:(Note: I am mentioning only methods, as they are easiest to picture when it comes to inheritance and mixing-in, but the same applies to other features.)