views:

86

answers:

2

A predefined set of objects has to be aggregated into a new object. However I want the users to specify a custom function for that.

Now the naive approach would be

def foo; end

objects = [1,2,3]
# result = eval(user_script)
result = eval("objects.inject {|sum, n| sum + n }")

What I obviously do not want to do! I read about $SAFE = 4 (see here), but I'm not sure that this is enough. Especially because the user-defined script will still be able to call other functions like foo. I only want to allow access to basic non-dangerous Ruby core-functions.

Are there any facilities for Ruby to allow safe execution of user-defined scripts? I doesn't need to be Ruby syntax. It would be nice, though.

A: 

The best lock in the world won't prevent you from being robbed blind if you choose to give everyone in the world the key.

Azeem.Butt
Indeed, that's why I only give moderators the right to add such code.
Marcel J.
+2  A: 

Have you seen Sven Fuch's safemode plugin (overview here)? Here's the page at GitHub.

Instead of blacklisting dangerous methods, which is what $SAFE does, it parses the incoming code and removes any method not on a whitelist. The plugin comes with a predefined whitelist that can be seen in this file.

I've personally never used this plugin but the author is active in the Ruby community and I'm sure he'd answer any questions you asked.

Mark Westling
This is great! Difficult to find such things in the rubyverse.
Marcel J.