Created
June 24, 2009 09:29
-
-
Save trans/135120 to your computer and use it in GitHub Desktop.
Shadow Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Quickly create shadow methods, eg. #__foo__ from #foo. | |
# This has a very limited use case, just use alias_method instead. | |
class Module | |
# Define a shadow alias for a method. | |
# | |
# class X | |
# shadow_method( :class ) | |
# end | |
# | |
# X.new.__class__ #=> X | |
# | |
def shadow_method( name, old_name=name ) | |
name, old_name = name.to_s, old_name.to_s | |
shadow_name = '__' << name.gsub(/([=?!])$/, '') << '__' << $1.to_s | |
alias_method( shadow_name, old_name ) | |
end | |
# Creates a shadow method for every currently defined method. | |
def shadow_all( include_ancestors=true ) | |
instance_methods(include_ancestors).each { |m| shadow_method( m ) } | |
end | |
end | |
=begin test | |
require 'test/unit' | |
class TCModule < Test::Unit::TestCase | |
class X | |
shadow_method( :inspect ) | |
end | |
def test_shadow_method | |
assert( X.new.respond_to?(:__inspect__) ) | |
end | |
end | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment