public
Created

Wrap all methods with a specific code

  • Download Gist
method-wrap.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 
class Foo
def self.method_added(m)
t = Thread.current
 
unless t[:_hook]
t[:_hook] = true
begin
alias_method "_#{m}", m
 
class_eval %Q{def #{m}(*a, &b)
bak = Process.euid
begin
_#{m}(*a, &b)
ensure
Process.euid = bak
end
end}
ensure
t[:_hook] = false
end
end
end
 
def x(a)
puts a
end
end
 
Foo.new.x 1

2 questions that I don't understand.

  1. what is thread for?

  2. def #{m} (*a)
    bak...
    begin
    _#{m} (*a)
    ensure
    end
    end

do we really need &b?

oh. i'm jarodzz in ruby-talk.

thanks again for this nice solution.

got it.
the (*a, &b) is for block args.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.