Class: CodeEvaluation

Inherits:
Object show all
Defined in:
lib/util/CodeEvaluation.rb

Constant Summary collapse

@@COUNT =

TODO I should cap the number of CodeEvaluation classes that can be created

0

Instance Method Summary collapse

Instance Method Details

#evaluate_code(code) ⇒ Object

Generates a class and dumps the passed in code into the a runtime method within the class and then runs it.

Parameters:

  • code

    Ruby code as a string



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/util/CodeEvaluation.rb', line 11

def evaluate_code(code)  
  @@COUNT += 1
  
  begin
    
    # Create file to include the test method 
    file = Tempfile.new("runtime_code_evaluation_#{@@COUNT}.rb")
    
    # Include the sytax for the statement in the file
    file << "class RuntimeCodeEvaluation#{@@COUNT}"+"\n"
    file << "\t"+'def check'+"\n"
    code.each_line do |l|
      file << "\t\t"+l+"\n"
    end
    file << "\t"+'end'+"\n"
    file << 'end'
    file.close
    
    # Load the newly created class and check the statement
    load file.path

    return eval("RuntimeCodeEvaluation#{@@COUNT}.new.check")
  ensure 
    file.close
    file.unlink      
  end
end