Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in Ruby/Rails to execute code that is in a string?

So I have a database of different code samples (read snippets). The code samples are created by users. Is there a way in Rails to execute it?

So for example I have the following code in my database (with id=123):

return @var.reverse 

Is there a way for me to execute it? Something like:

@var = 'Hello' @result = exec(CodeSample.find(123)) 

So the result would be 'olleH'

like image 832
Zepplock Avatar asked Jul 27 '09 15:07

Zepplock


People also ask

How do I show a string in Ruby?

To display a string in your program, you can use the print method: print "Let's print out this string." The print method displays the string exactly as written. print 'This is the first string.

What does #{} mean in Ruby?

It is for String Interpolation.. In Ruby, there are three ways of interpolation, and #{} is just one way. apples = 4 puts "I have #{apples} apples" # or puts "I have %s apples" % apples # or puts "I have %{a} apples" % {a: apples}


2 Answers

You can use eval:

code = '@var.reverse' @var = 'Hello' @result = eval(code)  # => "olleH" 

But be very careful in doing so; you're giving that code full access to your system. Try out eval('exit()') and see what happens.

like image 153
Pesto Avatar answered Sep 24 '22 19:09

Pesto


To the eval answer (which is the right one) I would add: get thee a copy of the Pickaxe Book (either Programming Ruby or Programming Ruby 1.9 depending on your Ruby version) and read the chapter called "Locking Ruby in the Safe." That chapter is all about Ruby's safe levels and tainted objects, and the chapter opens with exactly your use case and why you need to be paranoid about it.

like image 33
SFEley Avatar answered Sep 21 '22 19:09

SFEley