On 2/13/10, Jan Roslind <jan / jan-roslind.dk> wrote:
> Is there a way to include "raw" ruby source code in ruby method, or an
> more OO way to get a variable stack with local and instance variables?

It seems to me that a macro is the best way to get to almost what you
want. Take a look at this: http://github.com/coatl/rubymacros and/or
try typing 'gem install rubymacros' in a terminal.

Here's a macro that injects a rescue clause into method definitions:

macro rescuing_vars(method)
  method.body=:(
     begin
        ^method.body
     rescue => e; VariableStack.save_variables(binding, self) ; raise
     end
  )
  return method
end

You would then use it like this:

rescuing def foo
  bar baz, quux
end
#try to think of the 'rescuing' here as a
#declaration modifier, like 'static', 'inline', or 'const' in C++

which the above macro turns into:

def foo
  begin
    bar baz, quux
  rescue => e; VariableStack.save_variables(binding, self) ; raise
  end
end

You still have to go and mark each method in your program with the
rescuing tag, which is why I say it's only almost what you want. On
the plus side, you get control over which methods have their behavior
changed in this way.

You could also accomplish more or less the same thing if you keep your
method bodies in strings which get passed to eval, or blocks which get
passed to instance_eval, but that looks even less like normal ruby
code. On the other hand, you wouldn't need a special library
(rubymacros) that makes strange changes to ruby's syntax...

There may also be a better way to implement your algorithm without all
the metaprogramming magic. Sometimes when you think you need something
really strange that doesn't seem to exist, it's because you're
thinking about the problem in the wrong way.