[英]Save user input as it is - Ruby on Rails
I am trying to create an Online Judge where users will write/paste c++ code to evaluate it.我正在尝试创建一个在线法官,用户将在其中编写/粘贴 c++ 代码来评估它。 I'm using rails 6 and Ruby 2.6.1 .
我正在使用 rails 6 和Ruby 2.6.1 。 The problem is users' input can contain any type characters \n , \t etc. I need to save it to a cpp file as it is.
问题是用户的输入可以包含任何类型的字符\n , \t等。我需要将其保存到 cpp 文件中。 For example a user is submitting the following code:
例如,用户正在提交以下代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout << "Hello World\n";
}
I am using the following Ruby method to save the user input to a file我正在使用以下 Ruby 方法将用户输入保存到文件
system("echo '#{params[:code]}' > code.cpp")
My expected output is to be same as the user input.我预期的 output 与用户输入相同。 But I'm getting the following output to the saved file.
但是我得到以下 output 到保存的文件。
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout << "Hello World
";
}
Which is problematic, because it results in compilation error.这是有问题的,因为它会导致编译错误。 So my question is how can I SAFELY save the users' input as it is.
所以我的问题是我怎样才能安全地保存用户的输入。
Use an actual Ruby method:使用实际的 Ruby 方法:
File.open('code.cpp', 'w') { |f| f.write(params[:code]) }
Or shorter:或更短:
File.write('code.cpp', params[:code])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.