Created
May 21, 2010 20:42
-
-
Save ccooke/409390 to your computer and use it in GitHub Desktop.
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
module Abominate | |
def replace_object new_object | |
raise Exception.new( "Ia! Ia! Cthulhu Fhtagn!" ) unless instance_variable_defined? "@i_know_this_is_an_abomination" | |
context = class << self ; self ; end | |
new_object.instance_variables.each do |var| | |
instance_variable_set( var, new_object.instance_variable_get( var ) ) | |
end | |
instance_variables.each do |var| | |
remove_instance_variable( var ) unless new_object.instance_variable_defined? var | |
end | |
self.methods.each do |method_name| | |
meth = method_name.to_sym | |
unless new_object.respond_to? meth then | |
context.instance_eval do | |
define_method meth do | |
raise NoMethodError.new( "undefined method `#{ method_name }' for #{ self.inspect }:#{ new_object.class }" ) | |
end | |
end | |
end | |
end | |
new_object.methods.each do |method_name| | |
meth = method_name.to_sym | |
callable = new_object.method( meth ) | |
begin | |
context.instance_eval do | |
define_method meth do |*args| | |
callable.call( *args ) | |
end | |
end | |
rescue TypeError | |
end | |
end | |
self | |
end | |
end | |
class String | |
include Abominate | |
attr_writer :i_know_this_is_an_abomination | |
end | |
i = "hello world" | |
# => "hello world" | |
i.i_know_this_is_an_abomination = true | |
i.replace_object 100 | |
i | |
# => 100 | |
i.class | |
# => Fixnum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment