A few questions about the code below:
- Why do m1 and m2 have different IDs but compare as equal?
- Why does m2 invoke the same old functionality when run?
- Why did my instance_variable_set not ‘take’?
I suspect all answers have something to do with where the methods are
being defined/shadowed, but I’ll be damned if I can figure them out.
slim:~/Desktop/test gavinkistner$ ls -Flag
total 8
drwxr-xr-x 3 staff 102 Dec 24 10:15 ./
drwx------ 34 staff 1156 Dec 24 10:15 …/
-rw-r–r-- 1 staff 734 Dec 24 10:20 override.rb
slim:~/Desktop/test gavinkistner$ cat override.rb
class Module
def override( method_name, &block )
orig_method = method( method_name )
new_name = “m#{rand(1000000000)}”
alias_method new_name, method_name
define_method( method_name, &block )
method( method_name ).instance_variable_set( :@__orig_method_name,
new_name )
end
def restore( method_name )
alias_method method_name, method( method_name
).instance_variable_get( :@__orig_method_name )
end
end
m1 = Kernel.method( :system )
system ‘ls’
Kernel.override( :system ){ |code| puts "#{code}
not allowed"}
m2 = Kernel.method( :system )
system ‘ls’
p m1, m2, m1==m2, m1.object_id, m2.object_id
m1.call( ‘ls’ )
m2.call( ‘ls’ )
Kernel.restore( :system )
m3 = Kernel.method( :system )
system ‘ls’
END
slim:~/Desktop/test gavinkistner$ ruby override.rb
override.rb
ls
not allowed
#<Method: Kernel.system>
#<Method: Kernel.system>
true
953400
953250
override.rb
override.rb
override.rb:11:in alias_method': nil is not a symbol (TypeError) from override.rb:11:in
restore’
from override.rb:26