Hans Sjunnesson
2/22/2007 7:37:00 PM
On Feb 22, 5:01 pm, Ben Bleything <b...@bleything.net> wrote:
> On Fri, Feb 23, 2007, Hans Sjunnesson wrote:
> > Where 'job' is a string containing ruby code.
> > The problem I'm having is that I need these jobs to evaluate in a
> > clean environment, uncluttered by the previous jobs. What I'd like is
> > something along the lines of this:
>
> > temp = Kernel.binding
> > code = lambda {eval(job)}
> > code.call
> > Kernel.binding = temp
>
> I have (what I believe to be) a similar problem in some code I'm working
> on. It allows plugins written by the user to be executed, but each time
> it needs a clean environment. I'm taking advantage of the fact that you
> can pass eval a binding in which to execute. I have a simple binding
> factory which just creates new instances of itself and returns their
> binding:
>
> class BindingFactory
> def self::get_binding
> return self.new.send( :binding )
> end
> end
>
> eval( action, BindingFactory.get_binding )
>
> For my purposes, it works like a charm:
>
> >> ex1 = "a = :sym"
> => "a = :sym"
> >> ex2 = "puts a"
> => "puts a"
> >> eval ex1, BindingFactory.get_binding
> => :sym
> >> eval ex2, BindingFactory.get_binding
>
> NameError: undefined local variable or method `a' for #<BindingFactory:0x406f60f4>
> from (irb):18:in `send'
> from (irb):18:in `get_binding'
> from (irb):24
> from :0
>
> Is that helpful?
>
> Ben
Helpful - yes, in finding out that using eval might not be what I'm
after.
I thought, at first, that a binding housed the entirety of a running
ruby process' context.
I'm wanting to run ruby snippets like the below:
require 'rake'
default = task :default do
# do stuff
end
default.invoke
But for my problem, I might be better off using Kernel::system, and
invoking ruby in an external process, even though I'd really like my
little code-snippet to be able to access, for instance, the Logger
I've set up in my queue-system.
I might get away with that by modifying your BindingFactory to pass
objects into the created binding as local variables. But stuff like
rake modify the running context in more ways than setting local
variables.