Sha256: fc06cd2169297727a1b5c66ac28c3e4e7b80fc34679473c22ff81429cd8a3fff

Contents?: true

Size: 1.07 KB

Versions: 11

Compression:

Stored size: 1.07 KB

Contents

class Module

  # Don't think we should bother making this private.
  # That sort of defeats some of the AOP usefulness of this.
  #private

  # Creates a new method wrapping the previous of
  # the same name. Reference to the old method
  # is passed into the new definition block
  # as the first parameter.
  #
  #   wrap_method( sym ) { |old_meth, *args|
  #     old_meth.call
  #     ...
  #   }
  #
  # Keep in mind that this can not be used to wrap methods
  # that take a block.

  def wrap_method( sym, &blk )
    raise ArgumentError, "method does not exist" unless method_defined?( sym )
    old = instance_method(sym)
    undef_method(sym)
    define_method(sym) { |*args| blk.call(old.bind(self), *args) }
  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCModule < Test::Unit::TestCase

    def fixture_method; "A"; end

    wrap_method( :fixture_method ) { |old| old.call + "B" }

    def test_wrap_method
      assert_equal( "AB", fixture_method )
    end

  end

=end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
facets-1.3.0 lib/facets/core/module/wrap_method.rb
facets-1.2.1 lib/facets/core/module/wrap_method.rb
facets-1.3.3 lib/facets/core/module/wrap_method.rb
facets-1.3.1 lib/facets/core/module/wrap_method.rb
facets-1.3.2 lib/facets/core/module/wrap_method.rb
facets-1.4.0 lib/facets/core/module/wrap_method.rb
facets-1.4.1 lib/facets/core/module/wrap_method.rb
facets-1.4.2 lib/facets/core/module/wrap_method.rb
facets-1.4.3 lib/facets/core/module/wrap_method.rb
facets-1.4.5 lib/facets/core/module/wrap_method.rb
facets-1.4.4 lib/facets/core/module/wrap_method.rb