Prepend

What Module#prepend allows us to do is insert a module in-front of the class it was prepended to:

module Before
end

class Example
  prepend Before
end

Example.ancestors
# => [Before, Example, Object, Kernel, BasicObject]

Ejemplo: Memoización

module Memoize

  def memoize(method)
    memoizer = Module.new do

      # Define a method in the module with the same name
      define_method method do
        @__memoized_results ||= {}

        if @__memoized_results.include? method
          @__memoized_results[method]
        else
          @__memoized_results[method] = super()
        end
      end

    end

    prepend memoizer
  end
end



Subsecciones

Casiano Rodriguez León 2015-01-07