1

I am trying to create an Online Judge where users will write/paste c++ code to evaluate it. I'm using rails 6 and 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. 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

system("echo '#{params[:code]}' > code.cpp")

My expected output is to be same as the user input. But I'm getting the following output to the saved file.

#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.

  • [Why should I not #include ?](https://stackoverflow.com/q/31816095/5910058) – Jesper Juhl May 18 '20 at 17:35
  • 1
    There is absolutely no reason why you would use system to create a file in ruby. https://ruby-doc.org/core-2.5.0/File.html – max May 18 '20 at 17:51

1 Answers1

2

Use an actual Ruby method:

File.open('code.cpp', 'w') { |f| f.write(params[:code]) }

Or shorter:

File.write('code.cpp', params[:code])
BroiSatse
  • 39,333
  • 7
  • 50
  • 80