Ruby/Rails 中有没有办法执行字符串中的代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1188893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way in Ruby/Rails to execute code that is in a string?
提问by Zepplock
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?
所以我有一个不同代码示例(阅读片段)的数据库。代码示例由用户创建。Rails 有没有办法执行它?
So for example I have the following code in my database (with id=123):
例如,我的数据库中有以下代码(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'
所以结果将是'olleH'
回答by Pesto
回答by SFEley
To the evalanswer (which is the right one) I would add: get thee a copy of the Pickaxe Book (either Programming Rubyor Programming Ruby 1.9depending 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 exactlyyour use case and why you need to be paranoid about it.
对于eval答案(这是正确的),我要补充一点:给你一本 Pickaxe Book(Programming Ruby或Programming Ruby 1.9,取决于你的 Ruby 版本)并阅读名为“Locking Ruby in the Safe”的章节。那一章都是关于 Ruby 的安全级别和被污染的对象,并且这一章开始时正是您的用例以及您为什么需要对此感到偏执。
回答by Tyrone Wilson
There is also another approach which you can use if you have a very limited use case or to limit the use cases.
如果您的用例非常有限或限制用例,您还可以使用另一种方法。
I had to use this approach to allow users to dynamically specify relative times e.g.3.months.ago
我不得不使用这种方法来允许用户动态指定相对时间,例如3.months.ago
I used a regex to sanitize the input from the users like so
我使用正则表达式来清理来自用户的输入,就像这样
PERMITTED_OPERATIONS = /^\{\%([1-9]\.(day|year|month|hour|minute)(s\.|\.)ago|Time\.now)\%\}$/
def permit?(operation)
return !PERMITTED_OPERATIONS.match(operation.to_s).nil?
end
You could extend the regex to allow for from_nowas well or create an array of regexes for permitted operations and loop over it.
您可以扩展正则表达式以允许from_now或为允许的操作创建一个正则表达式数组并循环遍历它。
Would welcome any comments on this approach.
欢迎对此方法提出任何意见。

