I hacked something together that provides for hooking of methods. Look
for a thread called “How I’d like method-wrapping to work…”. I can
send
it to you directly if you want to.
I’ll put it on the wiki as soon as I can access it again.
robert
“Grzegorz Dostatni” grzegorz@ee.ualberta.ca schrieb im Newsbeitrag
news:Pine.LNX.4.44.0306101627070.3875-100000@e5-05.ee.ualberta.ca…
I have a number of questions:
Is it possible to examine current stack frame in ruby. Or move up
in
the stack frame to find the local variables of the function that
called
you?
Can I put a hook that gets called whenever anyone or anything
accesses
a function AND/OR a variable within an object? I would like to
intercept
that call to create a nice wrapper.
This should be a really easy question to answer:
Class Foo @test = “Hello World”
end
Class Bar @test = Foo.new
def bar
puts @test.@test (???)
end
end
How do I access a local variable of an object pointed to as local
variable. Is is a scoping problem? Are they just not visible? Should I
make them public? Should I stand on a crossroads at midnight swinging
a
black cat in a circle thirteen times?
Please help.
Greg
"Many a man may look respectable, and yet be able to hide at will
behind
module A
define_hook(:length) do
puts "A#length"
prior
end
end
class String
include A
define_hook(:length) do
puts "I'm calculating the length"
prior
end
end
str = "abcde"
x = str.length
puts x
svg%
svg% b.rb
./hooks.rb:65: warning: instance_methods parameter will default to 'true' in Jan 2004
./hooks.rb:58:in `class_eval': (eval):1:in `class_eval': undefined method `length' for module `A' (NameError)
from ./hooks.rb:58:in `class_eval'
from ./hooks.rb:58:in `define_hook'
from ./b.rb:5
svg%
Yes, because you define the hook before the original method is defined.
If I find the time, I might try a second version that solves this problem.
After all this was just an explorative study and not production code.
Anyway, thank’s for pointing that out.
svg% cat b.rb
#!/usr/bin/ruby
require ‘hooks.rb’
module A
define_hook(:length) do
puts “A#length”
prior
end
end
Is there work under way for a general hooking mechanism?
Matz is planning one, but the syntax
is not final. And he prefers an explicit
:before, :after, and so on.
What else is there - :in_between? :-))
I assume he is right, that this is better,
but I am not sure why.
One thing that comes to mind is, that this way one might be able to
implement preconditions and postconditions IOW DBC - depending on what the
hooks are allowed to do.