MD Tawab Alam Khan
MD Tawab Alam Khan

Reputation: 188

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

Upvotes: 1

Views: 161

Answers (1)

BroiSatse
BroiSatse

Reputation: 44685

Use an actual Ruby method:

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

Or shorter:

File.write('code.cpp', params[:code])

Upvotes: 2

Related Questions