Ruby/Rails 中有没有办法执行字符串中的代码? [英] Is there a way in Ruby/Rails to execute code that is in a string?

查看:46
本文介绍了Ruby/Rails 中有没有办法执行字符串中的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个包含不同代码示例(阅读片段)的数据库.代码示例由用户创建.Rails 有没有办法执行它?

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?

例如,我的数据库中有以下代码(id=123):

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))

所以结果是'olleH'

So the result would be 'olleH'

推荐答案

您可以使用 eval:

You can use eval:

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

但这样做时要非常小心;您授予该代码对系统的完全访问权限.试试 eval('exit()') 看看会发生什么.

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.

这篇关于Ruby/Rails 中有没有办法执行字符串中的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆