Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created June 27, 2012 09:18
Show Gist options
  • Save rklemme/3002732 to your computer and use it in GitHub Desktop.
Save rklemme/3002732 to your computer and use it in GitHub Desktop.
Wrap all methods with a specific code
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
@jarodzz
Copy link

jarodzz commented Jun 28, 2012

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?

@jarodzz
Copy link

jarodzz commented Jun 28, 2012

oh. i'm jarodzz in ruby-talk.

thanks again for this nice solution.

@jarodzz
Copy link

jarodzz commented Jun 28, 2012

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment