From: David Masover Date: 2009-09-07T13:02:40+09:00 Subject: Re: Opinion: Scripting in a Ruby program On Sunday 06 September 2009 06:47:47 am Tristan Shelton wrote: > Hello all, I'm working on a small program -- and learning to love Ruby > all over again -- but I've come across a small dilemma: What if you want > to make a Ruby program that can be extended without modifying the > original code? That is, a Ruby script that can itself be scripted. Unless you have a problem with Ruby, the way to do this is generally to provide a framework. As others have pointed out, Rails is the obvious example. Indeed, one of the things that keeps me interested in Ruby, even when I keep seeing other cool little languages like IO and Erlang, is how expressive it is, particularly how easy it is to create DSLs. > What I'm thinking of is something that gives users the ability to do > basic math, access explicitly allowed methods and properties and maybe > even allow user defined variables available only to that script, while > disallowing any other use of the parent Ruby script. Something that is > to Ruby what Ruby, Perl and Python are to C/C++. If you have a legitimate use of this -- for example, if your "scripts" are coming from an untrusted source -- then your argument makes sense. Probably the easiest approach is to take a language that's designed for this -- for example, Javascript (so embed Spidermonkey). Probably the best approach is to figure out how to sandbox Ruby -- look at the Try Ruby project for an example (or at least an attempt). On the other hand, if you're talking about a user running your Ruby app locally, and potentially extending it themselves, what are you protecting them from, or yourself from? Unless you're using JRuby, they already have the source, so it's not an IP issue, right? Anything else sounds a bit like protecting users from themselves -- for example, it's like asking "How do you make a private method/variable that no one else can see?" Well, instance_eval is there for a reason. > I considered loading chunks of Ruby script and using eval() in a safe > context, That's why I'm thinking it might be an untrusted source. > and also considered creating a very simple interpreted > scripting language in Ruby, Depends how simple it is. This could certainly be very easy -- but on the other hand, it could grow faster than you mean, and if it's Turing-complete, and your app is at all popular, people _will_ be writing applications in it. Do you really want to be responsible for the next PHP, or VBA? So again... easy way might be roll your own parser, or embed Javascript. Hard (and right, IMO) way is to use Ruby -- eval in a safe context, or run it as a separate (unprivileged, chrooted) process, etc.