Sha256: 2bda971614f7eee36d470947daec1515c0f909fcdaa7106936cadd45c5d69c05

Contents?: true

Size: 984 Bytes

Versions: 5

Compression:

Stored size: 984 Bytes

Contents

class Module
  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

5 entries across 5 versions & 1 rubygems

Version Path
facets-0.9.0 lib/nano/module/wrap_method.rb
facets-1.0.0 lib/facet/module/wrap_method.rb
facets-1.0.3 packages/core/lib/facet/module/wrap_method.rb
facets-1.1.0 lib/facet/module/wrap_method.rb
facets-1.2.0 lib/facets/core/module/wrap_method.rb