wrap(wrapperFunction[, arg...]) -> Function

Returns a function “wrapped” around the original function.

Function#wrap distills the essence of aspect-oriented programming into a single method, letting you easily build on existing functions by specifying before and after behavior, transforming the return value, or even preventing the original function from being called.


String.prototype.capitalize = String.prototype.capitalize.wrap( 
  function(proceed, eachWord) { 
    if (eachWord && this.include(" ")) {
      // capitalize each word in the string
      return this.split(" ").invoke("capitalize").join(" ");
    } else {
      // proceed using the original function
      return proceed(); 

"hello world".capitalize()     // "Hello world" 
"hello world".capitalize(true) // "Hello World"