As part of my Quest to find a clean way to get #puts and #print to 'work' in ERB, I was experimenting with ways I thought I could redefine Kernel methods from within a method. Why don't test1 and test2 work in the following code?
module Kernel
alias_method :_puts, :puts
def puts(s); _puts "HIDDEN"; end
end
puts "1: I DON'T WANNA SEE THIS"
module Kernel
undef_method :puts
alias_method :puts, :_puts
end
puts "1: OK to see this"
def run_test1
Kernel.instance_eval{
alias_method :_puts, :puts
def puts(s); _puts "HIDDEN"; end
}
puts "2: I DON'T WANNA SEE THIS"
Kernel.instance_eval{
undef_method :puts
alias_method :puts, :_puts
}
puts "2: OK to see this"
end
run_test1
def run_test2
kb = Kernel.instance_eval{ binding }
eval( "alias_method :_puts, :puts", kb )
eval( 'def puts(s); _puts "HIDDEN"; end', kb )
puts "3: I DON'T WANNA SEE THIS"
eval( "undef_method :puts", kb )
eval( "alias_method :puts, :_puts", kb )
puts "3: OK to see this"
end
run_test2
[[Slim:~/Desktop] gavinkis% ruby -vW0 binding_test.rb
ruby 1.8.2 (2004-12-25) [powerpc-darwin8.0.0]
HIDDEN
1: OK to see this
2: I DON'T WANNA SEE THIS
2: OK to see this
HIDDEN