Sha256: a0d169fb860ae2bc8f0661bc99c5687db870b43bcf17f04626d0cc9bdf30e2ca

Contents?: true

Size: 1.01 KB

Versions: 1

Compression:

Stored size: 1.01 KB

Contents

class Module
  # Creates a new method for a pre-existing method. If _aliased_
  # is set to true (the default) then the old_method is called 
  # subsequent to calling the new definition IF the new call
  # returns nil, otherwise the return value of the new call is
  # returned.
  #
  # This can not be used to wrap methods that take a block.
  #
  #   require 'facet/module/redefine_method'
  #
  #   redefine_method( sym, aliased  ) { |*args| ... }
  #   
  def redefine_method( sym, aliased=true, &blk )
    raise ArgumentError, "method does not exist" unless method_defined?( sym )
    if aliased
      old = instance_method(sym)
      undef_method(sym)
      define_method(sym){ |*args|
        r = blk.call(*args)
        return r unless r.nil?
        return old.bind(self).call(*args)
      }
    else
      undef_method(sym)
      define_method(sym) { |*args| 
        return blk.call(*args)
      }
    end
  end
  
  # Private alias for redefine_method.
  alias_method( :redef, :redefine_method )
  private :redef

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facets-0.6.3 lib/facet/module/redefine_method.rb