3

I have the following code:

code = "def hi; \"hi!\"; end"
eval code

hi == "hi!" # true

I can access the method hi, because when it is defined in the evaluated code, it is defined as a method of the main object.

However, this also means that the evaluated code can access things I define outside of it:

def hi; "hi!"; end
eval "hi == \"hi\"" # => true

I want to have a separate namespace in which I can run evaluated code; How would I do it?

I tried playing with module_eval and using a module for the namespace, but I can't get it to define a method or a class and access that in another evaluation.

0

2 Answers 2

3

You can evaluate code inside of an object like this:

  module DSL
    def helper_method_to_be_used_by_evaled_code
      # ...
    end

    # ...
  end

  container = Object.new
  container.extend(DSL)
  File.open(eval_file1, 'r') {|f| container.instance_eval(f.read, eval_file1)}
  File.open(eval_file2, 'r') {|f| container.instance_eval(f.read, eval_file2)}

With this you can control whether to preserve definitions between evals or not: you can reuse container instance or dispose it and create new one. This would work with method definitions and constants, local variables aren't preserved between such calls.

Also, instead of Object you may want to look at BlankState pattern. "blankslate" is an example.

Sign up to request clarification or add additional context in comments.

Comments

0

It doesn't seem like you're talking about making the module part of the evaluated code, so something like this should work just fine:

module EvalMethods
  class << self
    code = "def hi; \"hi!\"; end"
    eval code
  end
end

puts EvalMethods::hi == "hi!"

1 Comment

I need to be able to then perform a second eval in which I can access any previous definitions.. how could I do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.