简体   繁体   English

如何将 Ruby 脚本与 object 关联并按需执行(在 Rails 中)?

[英]How do I associate a Ruby script with an object and execute it on demand (in Rails)?

I'm interested in uploading a script (file) via my Rails application and then being able to execute this on demand.我有兴趣通过我的 Rails 应用程序上传脚本(文件),然后能够按需执行。

I imagine the first step here is to handle the file upload such that I a Model which I can reference the file like Model.script .我想这里的第一步是处理文件上传,这样我就可以使用Model ,我可以参考Model.script之类的文件。 This makes sense to me.这对我来说很有意义。

And then from here, my plan is to expose a route/controller method which would execute this script, but I'm not sure how to handle the actual execution inside this method.然后从这里开始,我的计划是公开一个将执行此脚本的路由/控制器方法,但我不确定如何处理此方法中的实际执行。 For example if I had例如,如果我有

class Model
  def run_script
    # logic to run self.script
  end
end

How would I execute the associated file/code given that it is a Ruby file?鉴于它是 Ruby 文件,我将如何执行关联的文件/代码? Note that the script does not need to run in the context of the Rails application, it just needs to run.请注意,脚本不需要在 Rails 应用程序的上下文中运行,它只需要运行即可。

You can use eval , which will run a Ruby script, but be very, very, careful!您可以使用eval ,它将运行 Ruby 脚本,但要非常非常小心!

For a detailed explanation see " Code is data, data is code ".详细解释见“ 代码即数据,数据即代码”。

Example:例子:

eval(@model_instance.script)

eval is very dangerous. eval非常危险。 If you give a user the ability to upload and run an unchecked script, it may create a huge problem.如果您让用户能够上传和运行未经检查的脚本,则可能会产生巨大的问题。 For example, someone can upload a script like this:例如,有人可以上传这样的脚本:

User.delete_all

This will delete all users from the users table using a SQL query without invoking any Active Record callbacks.这将使用 SQL 查询从users表中删除所有用户,而不调用任何 Active Record 回调。

You can use Ruby's taint method to add some additional safety, but it is not 100% foolproof.您可以使用 Ruby 的taint方法来增加一些额外的安全性,但它不是 100% 万无一失的。

For a detailed example, see " Locking Ruby in the Safe ".有关详细示例,请参阅“将 Ruby 锁定在保险箱中”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM