Tutorial :Using other languages with ruby


Is it possible to use multiple languages along side with ruby. For example, I have my application code in Ruby on Rails. I would like to calculate the recommendations and I would like to use python for that. So essentially, python code would get the data and calculate all the stuff and probably get the data from DB, calculate and update the tables.Is it possible and what do you guys think about its adv/disadv



If you are offloading work to an exterior process, you may want to make this a webservice (ajax, perhaps) of some sort so that you have some sort of consistent interface.

Otherwise, you could always execute the python script in a subshell through ruby, using stdin/stdout/argv, but this can get ugly quick.


I would use the system command as such

system("python myscript.py")  


Depending on your exact needs, you can either call out to an external process (using popen, system, etc) or you can setup another mini-web-server or something along those lines and have the rails server communicate with it over HTTP with a REST-style API (or whatever best suits your needs).

In your example, you have a ruby frontend website and then a number-crunching python backend service that builds up recommendation data for the ruby site. A fairly nice solution is to have the ruby site send a HTTP request to the python service when it needs data updating (with a payload of information to identify what it needs doing to what or some such) and then the python backend service can crunch away and update the table which presumably your ruby frontend will automatically pick up the changes of during the next request and display.


An easy, quick 'n' dirty solution in case you have python scripts and you want to execute them from inside rails, is this:

%x[shell commands or python path/of/pythonscript.py #{ruby variables to pass on the script}]


``shell commands or python path/of/pythonscript.py #{ruby variables to pass on the script}\ (with ` symbol in the beginning and the end).

Put the above inside a controller and it will execute.

For some reason, inside ruby on rails, system and exec commands didn't work for me (exec crashed my application and system doesn't do anything).

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »